Verified contractExactBSD-3-Clause
EBrake
Address0x0dab769617b2d690ddbe8a6d730d9c9b85f26ca0
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- BSD-3-Clause
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,297,190
- Creation transaction
- 0x1125bf9858…9f50aa9079
17 files
- contracts/EmergencyBrake/EBrake.solmain20.86 KB
- @openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol2.54 KB
- @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol3.17 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol6.64 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol2.75 KB
- @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol9.38 KB
- @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol1.48 KB
- @openzeppelin/contracts/access/IAccessControl.sol2.92 KB
- @venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol3.49 KB
- @venusprotocol/governance-contracts/contracts/Governance/IAccessControlManagerV8.sol858 B
- @venusprotocol/oracle/contracts/interfaces/OracleInterface.sol615 B
- contracts/EmergencyBrake/IEBrake.sol31.72 KB
- contracts/Interfaces/IComptroller.sol7.25 KB
- contracts/Interfaces/ICorePoolComptroller.sol4.49 KB
- contracts/Interfaces/IHubLiquidity.sol7.25 KB
- contracts/Interfaces/IILComptroller.sol1.8 KB
- contracts/Interfaces/IVToken.sol1.7 KB
contracts/EmergencyBrake/EBrake.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.25;
import { ICorePoolComptroller } from "../Interfaces/ICorePoolComptroller.sol";
import { IComptroller } from "../Interfaces/IComptroller.sol";
import { IILComptroller } from "../Interfaces/IILComptroller.sol";
import { IVToken } from "../Interfaces/IVToken.sol";
import { IEBrake } from "./IEBrake.sol";
import { IHub, IYieldGroupNav } from "../Interfaces/IHubLiquidity.sol";
import { AccessControlledV8 } from "@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol";
/**
* @title EBrake — Emergency Brake Contract
* @author Venus Protocol
* @notice Emergency action router for Venus Protocol (deployed behind a TransparentUpgradeableProxy).
* This contract holds NO detection logic — it only exposes Comptroller and Liquidity Hub
* emergency functions behind ACM permissions. See IEBrake for full design documentation.
*/
contract EBrake is IEBrake, AccessControlledV8 {
/// @notice Snapshot of a market's pre-incident state, captured by EBrake before tightening.
/// @dev Structs with nested mappings cannot be returned from external functions;
/// use getMarketCFSnapshot() to read per-pool CF/LT values.
/// Cap fields (borrowCap, supplyCap, etc.) are accessible via the auto-generated marketStates() getter.
/// @param borrowCap The borrow cap value before EBrake decreased it.
/// @param supplyCap The supply cap value before EBrake decreased it.
/// @param borrowCapSnapshotted True if a borrow cap snapshot has been recorded.
/// @param supplyCapSnapshotted True if a supply cap snapshot has been recorded.
/// @param poolCFs Mapping of poolId to the collateral factor before EBrake decreased it.
/// @param poolLTs Mapping of poolId to the liquidation threshold at snapshot time.
struct MarketState {
uint256 borrowCap;
uint256 supplyCap;
bool borrowCapSnapshotted;
bool supplyCapSnapshotted;
mapping(uint96 => uint256) poolCFs;
mapping(uint96 => uint256) poolLTs;
}
/**
* @notice Venus Core Pool Comptroller
* @dev The Diamond-only functions act on this comptroller, and the per-market functions act on it for
* its own markets. Markets of another comptroller are acted on through that comptroller.
* On BSC this is a Diamond proxy; on non-BSC chains it is an IL comptroller
*/
ICorePoolComptroller public immutable COMPTROLLER;
/**
* @notice True on chains other than BSC, where COMPTROLLER is an isolated-pools (IL) comptroller; false on BSC,
* where COMPTROLLER is the Diamond (venus-protocol repo).
* @dev Determines which ABI path decreaseCF(address,uint256) uses for markets of COMPTROLLER.
* Markets of any other comptroller always take the IL path.
*/
bool public immutable IS_REMOTE_CHAIN;
/// @notice Stored pre-incident market state snapshots, keyed by vToken market address.
/// @dev Values are captured at tightening time (first-write-wins) and cleared via resetCFSnapshot(),
/// resetBorrowCapSnapshot() and resetSupplyCapSnapshot().
mapping(address => MarketState) public marketStates;
/// @dev Storage gap for future upgrades.
uint256[49] private __gap;
/// @custom:oz-upgrades-unsafe-allow constructor
/// @param corePoolComptroller_ Address of the Venus Comptroller.
/// @param isRemoteChain_ True on chains other than BSC (COMPTROLLER is an IL comptroller), false on BSC (Diamond).
constructor(ICorePoolComptroller corePoolComptroller_, bool isRemoteChain_) {
if (address(corePoolComptroller_) == address(0)) revert ZeroAddress();
COMPTROLLER = corePoolComptroller_;
IS_REMOTE_CHAIN = isRemoteChain_;
_disableInitializers();
}
/// @notice Initialize the EBrake proxy with the Access Control Manager.
/// @param accessControlManager_ Address of the Venus Access Control Manager.
function initialize(address accessControlManager_) external initializer {
if (accessControlManager_ == address(0)) revert ZeroAddress();
__AccessControlled_init(accessControlManager_);
}
/// @inheritdoc IEBrake
function pauseActions(address[] calldata markets, IComptroller.Action[] calldata actions) external {
_checkAccessAllowed("pauseActions(address[],uint8[])");
if (markets.length == 0 || actions.length == 0) revert EmptyArray();
uint256 actionsLen = actions.length;
for (uint256 i; i < actionsLen; ++i) {
_validateAction(actions[i]);
}
IComptroller(_ensureSameComptroller(markets)).setActionsPaused(markets, actions, true);
emit ActionsPaused(msg.sender, markets, actions);
}
/// @inheritdoc IEBrake
function pauseSupply(address market) external {
_checkAccessAllowed("pauseSupply(address)");
_pauseSingleAction(market, IComptroller.Action.MINT);
emit ActionPaused(msg.sender, market, IComptroller.Action.MINT);
}
/// @inheritdoc IEBrake
function pauseRedeem(address market) external {
_checkAccessAllowed("pauseRedeem(address)");
_pauseSingleAction(market, IComptroller.Action.REDEEM);
emit ActionPaused(msg.sender, market, IComptroller.Action.REDEEM);
}
/// @inheritdoc IEBrake
function pauseBorrow(address market) external {
_checkAccessAllowed("pauseBorrow(address)");
_pauseSingleAction(market, IComptroller.Action.BORROW);
emit ActionPaused(msg.sender, market, IComptroller.Action.BORROW);
}
/// @inheritdoc IEBrake
function pauseTransfer(address market) external {
_checkAccessAllowed("pauseTransfer(address)");
_pauseSingleAction(market, IComptroller.Action.TRANSFER);
emit ActionPaused(msg.sender, market, IComptroller.Action.TRANSFER);
}
/// @inheritdoc IEBrake
function pauseFlashLoan() external {
_checkAccessAllowed("pauseFlashLoan()");
// Idempotent: skip the external call AND the event when already paused.
// Keeps FlashLoanPaused a true state-change signal for off-chain consumers
// and matches the "EBrake duplicate calls are no-ops" contract callers rely on.
if (COMPTROLLER.flashLoanPaused()) return;
COMPTROLLER.setFlashLoanPaused(true);
emit FlashLoanPaused(msg.sender);
}
/// @inheritdoc IEBrake
function disablePoolBorrow(uint96 poolId, address market) external {
_checkAccessAllowed("disablePoolBorrow(uint96,address)");
// `false` is hardcoded — EBrake can only tighten, never loosen.
COMPTROLLER.setIsBorrowAllowed(poolId, market, false);
emit PoolBorrowDisabled(msg.sender, poolId, market);
}
/// @inheritdoc IEBrake
function revokeFlashLoanAccess(address account) external {
_checkAccessAllowed("revokeFlashLoanAccess(address)");
if (account == address(0)) revert ZeroAddress();
// Idempotent: skip the external call AND the event when already revoked.
// Keeps FlashLoanAccessRevoked a true state-change signal, consistent with
// the pauseFlashLoan() pattern.
if (!COMPTROLLER.authorizedFlashLoan(account)) return;
// `false` is hardcoded — EBrake can only revoke, never grant.
COMPTROLLER.setWhiteListFlashLoanAccount(account, false);
emit FlashLoanAccessRevoked(msg.sender, account);
}
/// @inheritdoc IEBrake
function pauseHub(address hub) external {
_checkAccessAllowed("pauseHub(address)");
if (hub == address(0)) revert ZeroAddress();
if (IHub(hub).hubPaused()) return;
IHub(hub).pauseHub();
emit HubPaused(msg.sender, hub);
}
/// @inheritdoc IEBrake
function pauseHubYieldGroup(address yieldGroup) external {
_checkAccessAllowed("pauseHubYieldGroup(address)");
if (yieldGroup == address(0)) revert ZeroAddress();
address hub = IYieldGroupNav(yieldGroup).hub();
if (IHub(hub).yieldGroupConfig(yieldGroup).paused) return;
IHub(hub).pauseYieldGroup(yieldGroup);
emit HubYieldGroupPaused(msg.sender, hub, yieldGroup);
}
/// @inheritdoc IEBrake
function pauseHubResource(address yieldGroup, address resource) external {
_checkAccessAllowed("pauseHubResource(address,address)");
if (yieldGroup == address(0) || resource == address(0)) revert ZeroAddress();
(, bool paused, ) = IYieldGroupNav(yieldGroup).resourceConfig(resource);
if (paused) return;
IYieldGroupNav(yieldGroup).pauseResource(resource);
emit HubResourcePaused(msg.sender, yieldGroup, resource);
}
/// @inheritdoc IEBrake
function decreaseCF(address market, uint256 newCF) external {
_checkAccessAllowed("decreaseCF(address,uint256)");
MarketState storage state = marketStates[market];
address comptroller = address(IVToken(market).comptroller());
if (_isIsolatedPool(comptroller)) {
IILComptroller.Market memory m = IILComptroller(comptroller).markets(market);
if (!m.isListed) revert MarketNotListed(0, market);
if (newCF > m.collateralFactorMantissa) {
revert CFExceedsCurrent(market, 0, m.collateralFactorMantissa, newCF);
}
if (newCF == m.collateralFactorMantissa) return;
_snapshotCF(state, 0, m.collateralFactorMantissa, m.liquidationThresholdMantissa);
IILComptroller(comptroller).setCollateralFactor(market, newCF, m.liquidationThresholdMantissa);
emit CollateralFactorDecreased(msg.sender, market, 0, newCF);
} else {
uint96 corePoolId = COMPTROLLER.corePoolId();
uint96 lastPoolId = COMPTROLLER.lastPoolId();
(bool isCorePoolListed, , , , , , ) = COMPTROLLER.poolMarkets(corePoolId, market);
if (!isCorePoolListed) revert MarketNotListed(corePoolId, market);
for (uint96 i = corePoolId; i <= lastPoolId; ++i) {
(bool isListed, uint256 currentCF, , uint256 currentLT, , , ) = COMPTROLLER.poolMarkets(i, market);
if (!isListed) continue;
// Skip pools already at or below newCF — can't tighten further, and no point
// calling setCollateralFactor with a value higher than the current one.
if (newCF >= currentCF) continue;
_snapshotCF(state, i, currentCF, currentLT);
uint256 err = COMPTROLLER.setCollateralFactor(i, market, newCF, currentLT);
if (err != 0) revert SetCollateralFactorFailed(err);
emit CollateralFactorDecreased(msg.sender, market, i, newCF);
}
}
}
/// @inheritdoc IEBrake
function decreaseCF(address market, uint96 poolId, uint256 newCF) external {
_checkAccessAllowed("decreaseCF(address,uint96,uint256)");
if (IS_REMOTE_CHAIN) revert NotSupportedOnRemoteChain();
(bool isListed, uint256 currentCF, , uint256 currentLT, , , ) = COMPTROLLER.poolMarkets(poolId, market);
if (!isListed) revert MarketNotListed(poolId, market);
if (newCF > currentCF) revert CFExceedsCurrent(market, poolId, currentCF, newCF);
if (newCF == currentCF) return;
_snapshotCF(marketStates[market], poolId, currentCF, currentLT);
uint256 err = COMPTROLLER.setCollateralFactor(poolId, market, newCF, currentLT);
if (err != 0) revert SetCollateralFactorFailed(err);
emit CollateralFactorDecreased(msg.sender, market, poolId, newCF);
}
/// @inheritdoc IEBrake
function setMarketBorrowCaps(address[] calldata markets, uint256[] calldata newBorrowCaps) external {
_checkAccessAllowed("setMarketBorrowCaps(address[],uint256[])");
uint256 marketsLen = markets.length;
if (marketsLen == 0) revert EmptyArray();
if (marketsLen != newBorrowCaps.length) revert ArrayLengthMismatch(marketsLen, newBorrowCaps.length);
IComptroller comptroller = IComptroller(_ensureSameComptroller(markets));
bool anyDecreased;
for (uint256 i; i < marketsLen; ++i) {
uint256 currentCap = comptroller.borrowCaps(markets[i]);
if (newBorrowCaps[i] > currentCap) {
revert CapExceedsCurrent(markets[i], currentCap, newBorrowCaps[i]);
}
// Only act when this element actually tightens. Equality is a no-op —
// neither the comptroller call nor the snapshot should fire, so that the
// first-write-wins sentinel is not polluted by a redundant call.
if (newBorrowCaps[i] < currentCap) {
anyDecreased = true;
MarketState storage state = marketStates[markets[i]];
if (!state.borrowCapSnapshotted) {
state.borrowCap = currentCap;
state.borrowCapSnapshotted = true;
}
}
}
if (anyDecreased) {
comptroller.setMarketBorrowCaps(markets, newBorrowCaps);
emit BorrowCapsDecreased(msg.sender, markets, newBorrowCaps);
}
}
/// @inheritdoc IEBrake
function setMarketSupplyCaps(address[] calldata markets, uint256[] calldata newSupplyCaps) external {
_checkAccessAllowed("setMarketSupplyCaps(address[],uint256[])");
uint256 marketsLen = markets.length;
if (marketsLen == 0) revert EmptyArray();
if (marketsLen != newSupplyCaps.length) revert ArrayLengthMismatch(marketsLen, newSupplyCaps.length);
IComptroller comptroller = IComptroller(_ensureSameComptroller(markets));
bool anyDecreased;
for (uint256 i; i < marketsLen; ++i) {
uint256 currentCap = comptroller.supplyCaps(markets[i]);
if (newSupplyCaps[i] > currentCap) {
revert CapExceedsCurrent(markets[i], currentCap, newSupplyCaps[i]);
}
// Only act when this element actually tightens. Equality is a no-op —
// neither the comptroller call nor the snapshot should fire, so that the
// first-write-wins sentinel is not polluted by a redundant call.
if (newSupplyCaps[i] < currentCap) {
anyDecreased = true;
MarketState storage state = marketStates[markets[i]];
if (!state.supplyCapSnapshotted) {
state.supplyCap = currentCap;
state.supplyCapSnapshotted = true;
}
}
}
if (anyDecreased) {
comptroller.setMarketSupplyCaps(markets, newSupplyCaps);
emit SupplyCapsDecreased(msg.sender, markets, newSupplyCaps);
}
}
// ═══════════════════════════════════════════════════════════════════════
// MARKET STATE SNAPSHOT — RESET & VIEW
// ═══════════════════════════════════════════════════════════════════════
/// @inheritdoc IEBrake
function resetCFSnapshot(address market) external {
_checkAccessAllowed("resetCFSnapshot(address)");
MarketState storage state = marketStates[market];
if (_isIsolatedPool(address(IVToken(market).comptroller()))) {
delete state.poolCFs[0];
delete state.poolLTs[0];
} else {
uint96 corePoolId = COMPTROLLER.corePoolId();
uint96 lastPoolId = COMPTROLLER.lastPoolId();
for (uint96 i = corePoolId; i <= lastPoolId; ++i) {
delete state.poolCFs[i];
delete state.poolLTs[i];
}
}
emit CFSnapshotReset(market);
}
/// @inheritdoc IEBrake
function resetBorrowCapSnapshot(address market) external {
_checkAccessAllowed("resetBorrowCapSnapshot(address)");
MarketState storage state = marketStates[market];
state.borrowCap = 0;
state.borrowCapSnapshotted = false;
emit BorrowCapSnapshotReset(market);
}
/// @inheritdoc IEBrake
function resetSupplyCapSnapshot(address market) external {
_checkAccessAllowed("resetSupplyCapSnapshot(address)");
MarketState storage state = marketStates[market];
state.supplyCap = 0;
state.supplyCapSnapshotted = false;
emit SupplyCapSnapshotReset(market);
}
/// @inheritdoc IEBrake
function getMarketCFSnapshot(address market, uint96 poolId) external view returns (uint256 cf, uint256 lt) {
MarketState storage state = marketStates[market];
cf = state.poolCFs[poolId];
lt = state.poolLTs[poolId];
}
// ═══════════════════════════════════════════════════════════════════════
// INTERNALS
// ═══════════════════════════════════════════════════════════════════════
/**
* @notice Snapshot collateral factor and liquidation threshold for a market in a specific pool.
* @dev First-write-wins: only records if poolCFs[poolId] == 0 (no prior snapshot).
* If CF was already 0 before EBrake acted, there is nothing to restore.
* @param state The MarketState storage reference for this market.
* @param poolId The pool ID.
* @param currentCF The current collateral factor before decreasing.
* @param currentLT The current liquidation threshold.
*/
function _snapshotCF(MarketState storage state, uint96 poolId, uint256 currentCF, uint256 currentLT) internal {
if (state.poolCFs[poolId] == 0 && currentCF > 0) {
state.poolCFs[poolId] = currentCF;
state.poolLTs[poolId] = currentLT;
}
}
/**
* @notice Wraps a single market and action into arrays for the comptroller's setActionsPaused.
* @param market The vToken market address.
* @param action The action to pause.
*/
function _pauseSingleAction(address market, IComptroller.Action action) internal {
address[] memory markets = new address[](1);
markets[0] = market;
IComptroller.Action[] memory actions = new IComptroller.Action[](1);
actions[0] = action;
IVToken(market).comptroller().setActionsPaused(markets, actions, true);
}
/**
* @notice Ensure every market of a batch shares one comptroller, and return it.
* @param markets The vToken market addresses, at least one.
* @return comptroller The comptroller to act on.
* @custom:error MarketsOnDifferentComptrollers if a market's comptroller differs from the first market's
*/
function _ensureSameComptroller(address[] calldata markets) internal view returns (address comptroller) {
comptroller = address(IVToken(markets[0]).comptroller());
uint256 marketsLen = markets.length;
for (uint256 i = 1; i < marketsLen; ++i) {
address other = address(IVToken(markets[i]).comptroller());
if (other != comptroller) revert MarketsOnDifferentComptrollers(comptroller, other);
}
}
/**
* @notice Whether the isolated-pools path (pool id 0) applies to `comptroller`.
* @dev False only for COMPTROLLER when it is a Diamond (IS_REMOTE_CHAIN = false). Any other comptroller
* is treated as an isolated-pools comptroller with pool id 0, which Spoke comptrollers are.
* @param comptroller The comptroller about to be acted on.
* @return True for the isolated-pools path, false for the Diamond path.
*/
function _isIsolatedPool(address comptroller) internal view returns (bool) {
return IS_REMOTE_CHAIN || comptroller != address(COMPTROLLER);
}
/**
* @notice Validates that an action is one of the allowed emergency actions.
* Only MINT (0), REDEEM (1), BORROW (2), and TRANSFER (6) are permitted.
* @param action The action to validate.
*/
function _validateAction(IComptroller.Action action) internal pure {
if (
action != IComptroller.Action.MINT &&
action != IComptroller.Action.REDEEM &&
action != IComptroller.Action.BORROW &&
action != IComptroller.Action.TRANSFER
) {
revert ForbiddenAction(action);
}
}
}
@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.0;
import "./OwnableUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2StepUpgradeable is Initializable, OwnableUpgradeable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
function __Ownable2Step_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable2Step_init_unchained() internal onlyInitializing {
}
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
require(pendingOwner() == sender, "Ownable2Step: caller is not the new owner");
_transferOwnership(sender);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized != type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @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 amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` 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 amount) external returns (bool);
}
@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
@openzeppelin/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.25;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol";
import "./IAccessControlManagerV8.sol";
/**
* @title AccessControlledV8
* @author Venus
* @notice This contract is helper between access control manager and actual contract. This contract further inherited by other contract (using solidity 0.8.13)
* to integrate access controlled mechanism. It provides initialise methods and verifying access methods.
*/
abstract contract AccessControlledV8 is Initializable, Ownable2StepUpgradeable {
/// @notice Access control manager contract
IAccessControlManagerV8 internal _accessControlManager;
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
/// @notice Emitted when access control manager contract address is changed
event NewAccessControlManager(address oldAccessControlManager, address newAccessControlManager);
/// @notice Thrown when the action is prohibited by AccessControlManager
error Unauthorized(address sender, address calledContract, string methodSignature);
function __AccessControlled_init(address accessControlManager_) internal onlyInitializing {
__Ownable2Step_init();
__AccessControlled_init_unchained(accessControlManager_);
}
function __AccessControlled_init_unchained(address accessControlManager_) internal onlyInitializing {
_setAccessControlManager(accessControlManager_);
}
/**
* @notice Sets the address of AccessControlManager
* @dev Admin function to set address of AccessControlManager
* @param accessControlManager_ The new address of the AccessControlManager
* @custom:event Emits NewAccessControlManager event
* @custom:access Only Governance
*/
function setAccessControlManager(address accessControlManager_) external onlyOwner {
_setAccessControlManager(accessControlManager_);
}
/**
* @notice Returns the address of the access control manager contract
*/
function accessControlManager() external view returns (IAccessControlManagerV8) {
return _accessControlManager;
}
/**
* @dev Internal function to set address of AccessControlManager
* @param accessControlManager_ The new address of the AccessControlManager
*/
function _setAccessControlManager(address accessControlManager_) internal {
require(address(accessControlManager_) != address(0), "invalid acess control manager address");
address oldAccessControlManager = address(_accessControlManager);
_accessControlManager = IAccessControlManagerV8(accessControlManager_);
emit NewAccessControlManager(oldAccessControlManager, accessControlManager_);
}
/**
* @notice Reverts if the call is not allowed by AccessControlManager
* @param signature Method signature
*/
function _checkAccessAllowed(string memory signature) internal view {
bool isAllowedToCall = _accessControlManager.isAllowedToCall(msg.sender, signature);
if (!isAllowedToCall) {
revert Unauthorized(msg.sender, address(this), signature);
}
}
}
@venusprotocol/governance-contracts/contracts/Governance/IAccessControlManagerV8.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.25;
import "@openzeppelin/contracts/access/IAccessControl.sol";
/**
* @title IAccessControlManagerV8
* @author Venus
* @notice Interface implemented by the `AccessControlManagerV8` contract.
*/
interface IAccessControlManagerV8 is IAccessControl {
function giveCallPermission(address contractAddress, string calldata functionSig, address accountToPermit) external;
function revokeCallPermission(
address contractAddress,
string calldata functionSig,
address accountToRevoke
) external;
function isAllowedToCall(address account, string calldata functionSig) external view returns (bool);
function hasPermission(
address account,
address contractAddress,
string calldata functionSig
) external view returns (bool);
}
@venusprotocol/oracle/contracts/interfaces/OracleInterface.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.25;
interface OracleInterface {
function getPrice(address asset) external view returns (uint256);
}
interface ResilientOracleInterface is OracleInterface {
function updatePrice(address vToken) external;
function updateAssetPrice(address asset) external;
function getUnderlyingPrice(address vToken) external view returns (uint256);
}
interface BoundValidatorInterface {
function validatePriceWithAnchorPrice(
address asset,
uint256 reporterPrice,
uint256 anchorPrice
) external view returns (bool);
}
contracts/EmergencyBrake/IEBrake.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.25;
import { IComptroller } from "../Interfaces/IComptroller.sol";
/**
* @title IEBrake
* @author Venus Protocol
* @notice Interface for the EBrake (Emergency Brake) contract.
* EBrake is an emergency action router that can only TIGHTEN restrictions,
* never loosen them. It also snapshots pre-incident values (CF, caps) so that
* governance can read and restore them via VIP. See resetCFSnapshot(),
* resetBorrowCapSnapshot() and resetSupplyCapSnapshot().
*
* @dev Design goals and integration patterns:
*
* 1. DIRECT ACCESS
* The Venus multisig is whitelisted. During an incident, the multisig can call
* any function here (pause, set caps, etc.) without going through governance.
*
* 2. ON-CHAIN MONITORING CONTRACTS
* Contracts like DeviationSentinel or any Venus monitoring contract are also whitelisted.
* They contain their own detection logic (e.g. price deviation checks) and call into EBrake
* when a threat is detected. Example: DeviationSentinel detects a price anomaly → calls
* EBrake.pauseSupply() or EBrake.decreaseCF(). The detection logic stays isolated in
* the monitor; EBrake only handles execution.
*
* 3. THIRD-PARTY MONITORS VIA SAFE MODULES
* External monitoring services (e.g. Hypernative) don't get direct whitelist access. Instead,
* for each service we create a dedicated Safe Module on our multisig. The Safe Module contains
* its own allowlist of which EBrake functions that service can call (e.g. Hypernative can only
* pause supply/borrow, not set caps). This keeps permission scoping outside of EBrake — each
* module enforces its own restrictions.
*
* SAFETY INVARIANT — "Do no harm to existing users":
*
* This contract can ONLY tighten restrictions, NEVER loosen them. If a whitelisted address
* is compromised, the worst outcome is a temporary freeze — never fund loss or liquidation.
*
* This contract intentionally CANNOT:
* - Unpause → EBrake can only pause, never unpause. Recovery is via governance VIP
* - Pause REPAY → users must always be able to repay to avoid liquidation
* - Pause SEIZE → liquidations must always work to prevent bad debt accumulation
* - Pause protocol → setProtocolPaused blocks repay + liquidation, same problem
* - Lower LT → lowering liquidation threshold would instantly make healthy
* positions liquidatable, harming innocent users
* - Increase caps → caps can only be decreased to reduce exposure, never increased
* - Enable forced → bypasses shortfall check entirely — ANY borrower becomes
* liquidation liquidatable even with healthy collateral ratio
* - Target individual → prevents griefing specific addresses via per-user forced
* users liquidation
* - Set close factor → increasing allows liquidators to seize larger portions of
* collateral in one tx
* - Change oracle → wrong oracle = mass mispricing = mass liquidations
* - Change liquidation → altering incentive changes liquidation economics for all users
* incentive
*
* Worst-case if EBrake is compromised:
* - Pauses minting/borrowing/redeeming/transfers (inconvenient, no fund loss)
* - Zeros supply/borrow caps (blocks new positions, existing ones unaffected)
* - Decreases collateral factor (blocks new borrows against asset, does NOT liquidate
* existing positions — that requires LT change, which EBrake cannot do)
* - Pauses flash loans (blocks flash loan attack vector, no user impact)
* - Pauses the Liquidity Hub (blocks deposits and redemptions; existing balances
* untouched, and emergencyReallocate still works)
* - Pauses a Hub YieldGroup or one of its resources (stops new deposits routing there, and
* user withdrawals skip it; the balance already there still counts toward NAV)
* Recovery: Governance VIP restores all parameters. Temporary freeze, not catastrophic.
*
* BSC vs NON-BSC DIFFERENCES:
*
* The IS_REMOTE_CHAIN immutable determines which comptroller ABI is used for COMPTROLLER
* (see OTHER COMPTROLLERS for markets of other comptrollers).
* It is set at deployment and cannot be changed.
*
* BSC (BNB Chain) — Diamond Comptroller (IS_REMOTE_CHAIN = false):
* - decreaseCF(market, newCF) — for markets of COMPTROLLER, iterates corePoolId to lastPoolId,
* applies newCF only to pools where currentCF > newCF; silently skips pools already at or
* below newCF.
* - decreaseCF(market, poolId, newCF) — targets a single pool (e.g. multisig use)
* - Uses poolMarkets() (7-value return) to read LT,
* calls setCollateralFactor(poolId, market, newCF, LT) which returns uint256 error code
* - Supports e-mode pools via poolId > 0
* - pauseFlashLoan() — flash loans only exist on Diamond
* - pauseHub(hub), pauseHubYieldGroup(yieldGroup), pauseHubResource(yieldGroup, resource)
* — the Liquidity Hub is BSC-only
* - disablePoolBorrow(poolId, market) — per-pool granular borrow disable, only on Diamond
* - revokeFlashLoanAccess(account) — remove a single account from the flash loan
* whitelist; flash loan whitelist only exists on Diamond
* - ACM permission strings use underscore prefix:
* _setActionsPaused, _setMarketBorrowCaps, _setMarketSupplyCaps
*
* Non-BSC chains — IL Comptroller (IS_REMOTE_CHAIN = true):
* - decreaseCF(market, newCF) — uses markets() (3-value return) to read LT,
* calls setCollateralFactor(market, newCF, LT) which returns void (no error code).
* Reverts if newCF > currentCF.
* - No poolId concept — only the core pool exists (other pools are deprecated)
* - decreaseCF(market, poolId, newCF) not granted ACM permission (no pool concept on IL)
* - pauseFlashLoan() not granted ACM permission (flash loans don't exist on IL)
* - pauseHub(address), pauseHubYieldGroup(address) and
* pauseHubResource(address,address) not granted ACM permission (no Liquidity Hub off BSC).
* These are EBrake's own roles; what EBrake must hold on the Hub side is `pauseHub()` and
* `pauseYieldGroup(address)` on the Hub, and `pauseResource(address)` on each YieldGroup.
* - ACM permission strings have no underscore:
* setActionsPaused, setMarketBorrowCaps, setMarketSupplyCaps
*
* All other functions (pauseActions, pauseSupply, pauseBorrow, pauseRedeem,
* pauseTransfer, setMarketBorrowCaps, setMarketSupplyCaps) are ABI-compatible
* across both comptroller types and work identically on all chains.
*
* OTHER COMPTROLLERS (e.g. SPOKE POOLS):
*
* The per-market functions (pauseActions, pauseSupply, pauseRedeem, pauseBorrow, pauseTransfer,
* decreaseCF(address,uint256), setMarketBorrowCaps, setMarketSupplyCaps) act on market.comptroller(),
* whoever the caller is.
* - For a market of a comptroller other than COMPTROLLER (Spoke pools run the isolated-pools
* codebase), decreaseCF(address,uint256) uses the IL ABI with pool id 0, whatever IS_REMOTE_CHAIN
* says. The pause and cap functions have the same ABI on both comptroller types.
* - EBrake can only act on a comptroller once governance grants EBrake these ACM permissions on it
* (no underscore prefix, uint256[] actions): setActionsPaused(address[],uint256[],bool),
* setCollateralFactor(address,uint256,uint256), setMarketBorrowCaps(address[],uint256[]) and
* setMarketSupplyCaps(address[],uint256[]). These grants decide which comptrollers EBrake reaches.
* - All markets of a batch must share one comptroller, otherwise the call reverts with
* MarketsOnDifferentComptrollers.
* Each ACM permission on EBrake covers every comptroller EBrake reaches. Callers that should only act on
* some pools check the market themselves.
* resetCFSnapshot picks its path the same way as decreaseCF(address,uint256).
* The Diamond-only functions (pauseFlashLoan, disablePoolBorrow, revokeFlashLoanAccess,
* decreaseCF(address,uint96,uint256)) only ever act on COMPTROLLER.
* Snapshots are keyed by market address, so Core and Spoke markets never share an entry.
*/
interface IEBrake {
// ═══════════════════════════════════════════════════════════════════════
// EVENTS
// ═══════════════════════════════════════════════════════════════════════
/// @notice Emitted when actions are paused on markets via batch pause.
/// @param caller The address that triggered the emergency action.
/// @param markets The vToken market addresses that were paused.
/// @param actions The actions that were paused.
event ActionsPaused(address indexed caller, address[] markets, IComptroller.Action[] actions);
/// @notice Emitted when a single action is paused on a market.
/// @param caller The address that triggered the emergency action.
/// @param market The vToken market address that was paused.
/// @param action The action that was paused.
event ActionPaused(address indexed caller, address indexed market, IComptroller.Action action);
/// @notice Emitted when flash loans are paused.
/// @param caller The address that triggered the emergency action.
event FlashLoanPaused(address indexed caller);
/// @notice Emitted when borrowing is disabled for a market in a specific pool.
/// @param caller The address that triggered the emergency action.
/// @param poolId The pool identifier (0 = core pool, >0 = e-mode pools).
/// @param market The vToken market address whose pool-borrow flag was disabled.
event PoolBorrowDisabled(address indexed caller, uint96 indexed poolId, address indexed market);
/// @notice Emitted when an account is removed from the flash loan whitelist.
/// @param caller The address that triggered the emergency action.
/// @param account The account whose flash loan access was revoked.
event FlashLoanAccessRevoked(address indexed caller, address indexed account);
/// @notice Emitted when a collateral factor is decreased.
/// Used for both core/e-mode pools and IL comptrollers.
/// @param caller The address that triggered the emergency action.
/// @param market The vToken market address whose CF was decreased.
/// @param poolId The pool ID. On BNB Chain (Diamond comptroller) this identifies the core pool (0)
/// or an e-mode pool (>0). IL comptrollers (non-BSC chains, Spoke pools) have no pool concept,
/// so 0 is used.
/// @param newCF The new collateral factor value that the market was set to.
event CollateralFactorDecreased(
address indexed caller,
address indexed market,
uint96 indexed poolId,
uint256 newCF
);
/// @notice Emitted when borrow caps are decreased.
/// @param caller The address that triggered the emergency action.
/// @param markets The vToken market addresses whose borrow caps were decreased.
/// @param newBorrowCaps The new borrow cap values.
event BorrowCapsDecreased(address indexed caller, address[] markets, uint256[] newBorrowCaps);
/// @notice Emitted when supply caps are decreased.
/// @param caller The address that triggered the emergency action.
/// @param markets The vToken market addresses whose supply caps were decreased.
/// @param newSupplyCaps The new supply cap values.
event SupplyCapsDecreased(address indexed caller, address[] markets, uint256[] newSupplyCaps);
/// @notice Emitted when a market's CF/LT snapshot is reset after governance recovery.
/// @param market The market address whose CF snapshot was cleared.
event CFSnapshotReset(address indexed market);
/// @notice Emitted when a market's borrow cap snapshot is reset after governance recovery.
/// @param market The market address whose borrow cap snapshot was cleared.
event BorrowCapSnapshotReset(address indexed market);
/// @notice Emitted when a market's supply cap snapshot is reset after governance recovery.
/// @param market The market address whose supply cap snapshot was cleared.
event SupplyCapSnapshotReset(address indexed market);
/// @notice Emitted when the Liquidity Hub was paused through EBrake.
/// @param caller The address that triggered the pause.
/// @param hub The Hub that was paused.
event HubPaused(address indexed caller, address indexed hub);
/// @notice Emitted when a Hub YieldGroup was paused through EBrake.
/// @param caller The address that triggered the pause.
/// @param hub The Hub the YieldGroup belongs to.
/// @param yieldGroup The YieldGroup that was paused.
event HubYieldGroupPaused(address indexed caller, address indexed hub, address indexed yieldGroup);
/// @notice Emitted when a resource inside a Hub YieldGroup was paused through EBrake.
/// @param caller The address that triggered the pause.
/// @param yieldGroup The YieldGroup that holds the resource.
/// @param resource The resource that was paused.
event HubResourcePaused(address indexed caller, address indexed yieldGroup, address indexed resource);
// ═══════════════════════════════════════════════════════════════════════
// ERRORS
// ═══════════════════════════════════════════════════════════════════════
/// @notice Thrown when a forbidden action (REPAY, SEIZE, etc.) is passed to batch pause.
/// @param action The disallowed action that was passed.
error ForbiddenAction(IComptroller.Action action);
/// @notice Thrown when a zero address is passed where a valid address is required.
error ZeroAddress();
/// @notice Thrown when a market is not listed in the given pool.
/// On BNB Chain (Diamond comptroller) poolId identifies the core pool (0) or an e-mode pool (>0).
/// IL comptrollers (non-BSC chains, Spoke pools) have no pool concept, so poolId is 0.
/// @param poolId The pool ID that was queried.
/// @param market The market address that is not listed.
error MarketNotListed(uint96 poolId, address market);
/// @notice Thrown when setCollateralFactor returns a non-zero error code.
/// @param errorCode The error code returned by the comptroller.
error SetCollateralFactorFailed(uint256 errorCode);
/// @notice Thrown when an empty array is passed where at least one element is required.
error EmptyArray();
/// @notice Thrown when array lengths do not match.
/// @param expected The expected array length.
/// @param actual The actual array length.
error ArrayLengthMismatch(uint256 expected, uint256 actual);
/// @notice Thrown when the requested cap exceeds the current cap on the comptroller.
/// @param market The market whose cap was attempted to be increased.
/// @param currentCap The current cap value on the comptroller.
/// @param requestedCap The new cap value that was rejected.
error CapExceedsCurrent(address market, uint256 currentCap, uint256 requestedCap);
/// @notice Thrown when a function is called that is not supported on remote chains (IS_REMOTE_CHAIN).
/// Pool ID is a Diamond-only concept — this function should never be ACM-granted on IL chains.
error NotSupportedOnRemoteChain();
/// @notice Thrown when the requested collateral factor exceeds the current CF on the comptroller.
/// EBrake can only tighten CF — newCF must be <= currentCF.
/// @param market The market whose CF was attempted to be increased.
/// @param poolId The pool ID where the violation was detected (0 on IL comptroller).
/// @param currentCF The current collateral factor on the comptroller.
/// @param requestedCF The new CF value that was rejected.
error CFExceedsCurrent(address market, uint96 poolId, uint256 currentCF, uint256 requestedCF);
/// @notice Thrown when a batch mixes markets of different comptrollers.
/// @param expected The comptroller of the first market in the batch.
/// @param actual The comptroller of the first market that differs from it.
error MarketsOnDifferentComptrollers(address expected, address actual);
// ═══════════════════════════════════════════════════════════════════════
// EMERGENCY ACTIONS — BATCH OPERATIONS
// ═══════════════════════════════════════════════════════════════════════
/**
* @notice Pause multiple actions on multiple markets in one call.
* @dev Only MINT, REDEEM, BORROW, and TRANSFER are allowed. Reverts on REPAY, SEIZE,
* LIQUIDATE, ENTER_MARKET, or EXIT_MARKET — see SAFETY INVARIANT.
* @param markets The vToken market addresses to pause actions on.
* @param actions The actions to pause.
*/
function pauseActions(address[] calldata markets, IComptroller.Action[] calldata actions) external;
// ═══════════════════════════════════════════════════════════════════════
// EMERGENCY ACTIONS — SINGLE MARKET PAUSING
// ═══════════════════════════════════════════════════════════════════════
/// @notice Pause supply (mint) on a single market.
/// Blocks new deposits. Existing suppliers can still redeem.
/// @param market The vToken market address.
function pauseSupply(address market) external;
/// @notice Pause redeem on a single market.
/// Blocks withdrawals. Use when draining must be stopped immediately.
/// @param market The vToken market address.
function pauseRedeem(address market) external;
/// @notice Pause borrow on a single market.
/// Blocks new borrows. Existing borrowers can still repay.
/// @param market The vToken market address.
function pauseBorrow(address market) external;
/// @notice Pause transfer of vTokens on a single market.
/// Blocks vToken movement, prevents attacker from moving stolen collateral.
/// @param market The vToken market address.
function pauseTransfer(address market) external;
// ═══════════════════════════════════════════════════════════════════════
// EMERGENCY ACTIONS — FLASH LOANS
// ═══════════════════════════════════════════════════════════════════════
/// @notice Pause flash loans across the core pool.
function pauseFlashLoan() external;
/**
* @notice Disable borrowing for a market in a specific pool, leaving other pools unaffected.
* @dev Only meaningful on Diamond comptroller (BSC) where the per-pool `isBorrowAllowed` flag exists.
* On non-BSC chains the underlying call will revert (selector mismatch on IL comptroller).
*
* This is independent of `pauseBorrow(market)` which flips the global
* `_actionPaused[market][BORROW]` flag across every pool. Both flags must allow borrowing
* for borrows to actually proceed in a given pool/market — recovery from a combined
* tightening therefore requires governance to clear both flags.
*
* The boolean argument is hardcoded to `false` inside the implementation to preserve
* the EBrake "tighten only, never loosen" invariant. Re-enabling borrow is governance-only.
* @param poolId The pool identifier (0 = core pool, >0 = e-mode pools).
* @param market The vToken market address.
*/
function disablePoolBorrow(uint96 poolId, address market) external;
/**
* @notice Remove a single account from the flash loan whitelist.
* @dev Only meaningful on Diamond comptroller (BSC) where the flash loan whitelist exists.
* On non-BSC chains the underlying call will revert (selector mismatch on IL comptroller).
*
* This is the surgical alternative to `pauseFlashLoan()`, which kills flash loans for
* every whitelisted account. Use it when a single whitelisted integrator is compromised.
*
* The boolean argument is hardcoded to `false` inside the implementation to preserve
* the EBrake "tighten only, never loosen" invariant. Re-granting access is governance-only.
*
* Idempotent: if the account is not currently whitelisted, the call is a no-op and
* no event is emitted. FlashLoanAccessRevoked is a true state-change signal.
* @param account The account whose flash loan access should be revoked.
*/
function revokeFlashLoanAccess(address account) external;
// ═══════════════════════════════════════════════════════════════════════
// EMERGENCY ACTIONS — LIQUIDITY HUB
// ═══════════════════════════════════════════════════════════════════════
/**
* @notice Pause the Liquidity Hub, halting deposits and redemptions.
* @dev Forwards to the Hub, which EBrake holds the `pauseHub()` ACM role on. Tighten-only —
* unpausing is a VIP against the Hub directly. An already-paused Hub is a no-op with no
* event, so {HubPaused} stays a true state-change signal, as {pauseFlashLoan} does.
* @param hub The Liquidity Hub to pause.
*/
function pauseHub(address hub) external;
/**
* @notice Stop a Hub routing new deposits to one YieldGroup. The balance already there still
* counts toward NAV, but user withdrawals skip it until governance unpauses it.
* @dev Forwards to the Hub the YieldGroup reports through `hub()`, which EBrake holds the
* `pauseYieldGroup(address)` ACM role on. Tighten-only, and an already-paused YieldGroup is
* a no-op with no event, as {pauseHub}. A YieldGroup the Hub never registered reads as
* unpaused, so the Hub's own `YieldGroupNotRegistered` revert comes back to the caller —
* which is also what stops a fake YieldGroup that names a real Hub.
* @param yieldGroup The YieldGroup to pause.
*/
function pauseHubYieldGroup(address yieldGroup) external;
/**
* @notice Stop a Hub YieldGroup routing new deposits to one of its resources. The balance
* already there still counts toward NAV, but user withdrawals skip it until governance
* unpauses it.
* @dev Forwards to the YieldGroup, which checks `pauseResource(address)` against its own
* address, so EBrake needs that grant on every YieldGroup it should reach. Tighten-only,
* and an already-paused resource is a no-op with no event, as {pauseHub}. A resource the
* YieldGroup never registered reads as unpaused, so its `ResourceNotRegistered` revert
* comes back to the caller.
* @param yieldGroup The YieldGroup that holds the resource.
* @param resource The resource to pause.
*/
function pauseHubResource(address yieldGroup, address resource) external;
// ═══════════════════════════════════════════════════════════════════════
// EMERGENCY ACTIONS — RISK PARAMETER ADJUSTMENTS
// ═══════════════════════════════════════════════════════════════════════
/**
* @notice Decrease collateral factor to `newCF` for a market across all relevant pools.
* Liquidation threshold is left unchanged.
* Blocks/limits new borrows against the asset. Does NOT make existing positions liquidatable —
* that would require lowering LT, which this contract cannot do.
* @dev On the Diamond (markets of COMPTROLLER, IS_REMOTE_CHAIN=false): iterates corePoolId to lastPoolId;
* applies `newCF` only to pools where currentCF > newCF (silently skips pools already
* at or below newCF and unlisted pools). Never reverts due to CF comparison — use the
* per-pool overload if you need strict enforcement on a specific pool.
* On an IL comptroller (IS_REMOTE_CHAIN=true, or a market of another comptroller such as a
* Spoke pool): applies to the single market entry with pool id 0 and
* reverts with CFExceedsCurrent if newCF > currentCF.
* @param market The vToken market address whose CF should be decreased.
* @param newCF The new collateral factor value. On Diamond, pools already at or below this
* value are silently skipped. On IL, must be <= current CF.
*/
function decreaseCF(address market, uint256 newCF) external;
/**
* @notice Decrease collateral factor to `newCF` for a market in a specific pool.
* Same safety guarantees as decreaseCF(address,uint256) — LT is left unchanged.
* @dev Only meaningful on Diamond comptroller (BSC) where multiple pools exist.
* Reverts with NotSupportedOnRemoteChain on IL chains — ACM must not grant this permission there.
* Reverts with CFExceedsCurrent if newCF > current CF in the targeted pool.
* @param market The vToken market address whose CF should be decreased.
* @param poolId The pool ID (0 for core pool, >0 for e-mode pools).
* @param newCF The new collateral factor value. Must be <= current CF in the targeted pool.
*/
function decreaseCF(address market, uint96 poolId, uint256 newCF) external;
/**
* @notice Decrease borrow caps on markets. Each new cap must be strictly LOWER than the current value.
* Elements equal to the current cap are silently skipped. Setting to 0 blocks all new borrows.
* Existing borrows are never affected by caps.
* @param markets The vToken market addresses to adjust borrow caps on.
* @param newBorrowCaps The new borrow cap values. Each must be < current cap (equality is a no-op, > reverts).
*/
function setMarketBorrowCaps(address[] calldata markets, uint256[] calldata newBorrowCaps) external;
/**
* @notice Decrease supply caps on markets. Each new cap must be strictly LOWER than the current value.
* Elements equal to the current cap are silently skipped. Setting to 0 blocks all new deposits.
* Existing deposits are never affected by caps.
* @param markets The vToken market addresses to adjust supply caps on.
* @param newSupplyCaps The new supply cap values. Each must be < current cap (equality is a no-op, > reverts).
*/
function setMarketSupplyCaps(address[] calldata markets, uint256[] calldata newSupplyCaps) external;
// ═══════════════════════════════════════════════════════════════════════
// MARKET STATE SNAPSHOT — RESET & VIEW
// ═══════════════════════════════════════════════════════════════════════
/**
* @notice Reset only the stored CF/LT snapshot for a market.
* @dev Called by governance as part of a recovery VIP after restoring collateral factors.
* Clears per-pool CF/LT values so that future EBrake actions can capture fresh
* pre-incident values. Does not touch cap snapshots.
* For a market of COMPTROLLER on the Diamond it clears pool ids corePoolId to lastPoolId; for any other
* market, pool id 0.
* @param market The vToken market address whose CF snapshot should be cleared.
*/
function resetCFSnapshot(address market) external;
/**
* @notice Reset only the stored borrow cap snapshot for a market.
* @dev Called by governance as part of a recovery VIP after restoring the borrow cap.
* Clears borrowCap and borrowCapSnapshotted so that future EBrake actions can capture
* a fresh pre-incident value. Does not touch the supply cap or CF snapshots.
* @param market The vToken market address whose borrow cap snapshot should be cleared.
*/
function resetBorrowCapSnapshot(address market) external;
/**
* @notice Reset only the stored supply cap snapshot for a market.
* @dev Called by governance as part of a recovery VIP after restoring the supply cap.
* Clears supplyCap and supplyCapSnapshotted so that future EBrake actions can capture
* a fresh pre-incident value. Does not touch the borrow cap or CF snapshots.
* @param market The vToken market address whose supply cap snapshot should be cleared.
*/
function resetSupplyCapSnapshot(address market) external;
/**
* @notice Read the stored collateral factor and liquidation threshold snapshot for a market in a specific pool.
* @param market The vToken market address.
* @param poolId The pool ID (0 for IL comptrollers, including Spoke pools, or the core pool on Diamond).
* @return cf The collateral factor that was stored before EBrake zeroed it. 0 if no snapshot exists.
* @return lt The liquidation threshold at the time of the snapshot. 0 if no snapshot exists.
*/
function getMarketCFSnapshot(address market, uint96 poolId) external view returns (uint256 cf, uint256 lt);
}
contracts/Interfaces/IComptroller.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.25;
import { ResilientOracleInterface } from "@venusprotocol/oracle/contracts/interfaces/OracleInterface.sol";
import { IVToken } from "./IVToken.sol";
/// @title IComptroller
/// @author Venus Protocol
/// @notice Interface for the Venus Comptroller with market management and risk parameter functions.
interface IComptroller {
enum Action {
MINT,
REDEEM,
BORROW,
REPAY,
SEIZE,
LIQUIDATE,
TRANSFER,
ENTER_MARKET,
EXIT_MARKET
}
/// @notice Pause or unpause specific actions on given markets.
/// @param markets_ The list of vToken market addresses.
/// @param actions_ The list of actions to pause/unpause.
/// @param paused_ True to pause, false to unpause.
function setActionsPaused(address[] calldata markets_, Action[] calldata actions_, bool paused_) external;
/// @notice Set borrow caps for the given markets.
/// @param vTokens The list of vToken market addresses.
/// @param newBorrowCaps The list of new borrow cap values.
function setMarketBorrowCaps(address[] calldata vTokens, uint256[] calldata newBorrowCaps) external;
/// @notice Set supply caps for the given markets.
/// @param vTokens The list of vToken market addresses.
/// @param newSupplyCaps The list of new supply cap values.
function setMarketSupplyCaps(address[] calldata vTokens, uint256[] calldata newSupplyCaps) external;
/// @notice Unlist a market from the comptroller.
/// @param vToken The vToken market address to unlist.
/// @return uint256 Error code (0 = success).
function unlistMarket(address vToken) external returns (uint256);
/// @notice Execute a flash loan.
/// @param onBehalf The address on whose behalf the flash loan is executed.
/// @param receiver The address receiving the flash loan funds.
/// @param vTokens The list of vToken markets to borrow from.
/// @param underlyingAmounts The list of underlying amounts to borrow.
/// @param param Additional parameters for the flash loan callback.
function executeFlashLoan(
address payable onBehalf,
address payable receiver,
IVToken[] memory vTokens,
uint256[] memory underlyingAmounts,
bytes memory param
) external;
/// @notice Enter multiple markets to use as collateral.
/// @param vTokens The list of vToken market addresses to enter.
/// @return uint256[] Error codes for each market (0 = success).
function enterMarkets(address[] calldata vTokens) external returns (uint256[] memory);
/// @notice Enter a market on behalf of another address.
/// @param onBehalf The address to enter the market for.
/// @param vToken The vToken market address.
/// @return uint256 Error code (0 = success).
function enterMarketBehalf(address onBehalf, address vToken) external returns (uint256);
/// @notice Enter a market for a specific user (internal comptroller use).
/// @param user The user address.
/// @param vToken The vToken market address.
/// @return uint256 Error code (0 = success).
function enterMarket(address user, address vToken) external returns (uint256);
/// @notice Enter a market for an account. The caller needs the ACM permission for `enterMarketForAccount(address,address)`.
/// @param account The account to enter the market for.
/// @param vToken The vToken market address.
/// @return uint256 Error code (0 = success).
function enterMarketForAccount(address account, address vToken) external returns (uint256);
/// @notice Check whether an action is paused on a given market.
/// @param market The vToken market address.
/// @param action The action to check.
/// @return bool True if the action is paused.
function actionPaused(address market, Action action) external view returns (bool);
/// @notice Get market information for a given vToken.
/// @param vToken The vToken market address.
/// @return isListed Whether the market is listed.
/// @return collateralFactorMantissa The collateral factor mantissa.
/// @return isComped Whether the market receives COMP/XVS rewards.
function markets(
address vToken
) external view returns (bool isListed, uint256 collateralFactorMantissa, bool isComped);
/// @notice Get the price oracle used by the comptroller.
/// @return ResilientOracleInterface The oracle contract.
function oracle() external view returns (ResilientOracleInterface);
/// @notice Check if an account has entered a given market.
/// @param account The account address.
/// @param vToken The vToken market to check membership for.
/// @return bool True if the account is a member of the market.
function checkMembership(address account, IVToken vToken) external view returns (bool);
/// @notice Get the borrowing power of an account.
/// @param account The account address.
/// @return error Error code (0 = success).
/// @return liquidity The account's excess liquidity.
/// @return shortfall The account's shortfall.
function getBorrowingPower(
address account
) external view returns (uint256 error, uint256 liquidity, uint256 shortfall);
/// @notice Get an account's liquidity as it would be after redeeming or borrowing in one market.
/// @param account The account address.
/// @param vTokenModify The vToken market the redeem or borrow applies to.
/// @param redeemTokens The amount of vTokens to redeem.
/// @param borrowAmount The amount of underlying to borrow.
/// @return error Error code (0 = success).
/// @return liquidity The account's excess liquidity.
/// @return shortfall The account's shortfall.
function getHypotheticalAccountLiquidity(
address account,
address vTokenModify,
uint256 redeemTokens,
uint256 borrowAmount
) external view returns (uint256 error, uint256 liquidity, uint256 shortfall);
/// @notice Get the treasury fee percentage.
/// @return uint256 The treasury percentage mantissa.
function treasuryPercent() external view returns (uint256);
/// @notice Get the borrow cap for a given market.
/// @param vToken The vToken market address.
/// @return uint256 The borrow cap.
function borrowCaps(address vToken) external view returns (uint256);
/// @notice Get the supply cap for a given market.
/// @param vToken The vToken market address.
/// @return uint256 The supply cap.
function supplyCaps(address vToken) external view returns (uint256);
/// @notice Check if a delegate is approved to borrow on behalf of a borrower.
/// @param borrower The borrower address.
/// @param delegate The delegate address.
/// @return bool True if the delegate is approved.
function approvedDelegates(address borrower, address delegate) external view returns (bool);
function getAccountLiquidity(address account) external view returns (uint256, uint256, uint256);
function exitMarket(address vToken) external returns (uint256);
function updateDelegate(address delegate, bool approved) external;
}
contracts/Interfaces/ICorePoolComptroller.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.25;
import { IComptroller } from "./IComptroller.sol";
/// @title ICorePoolComptroller
/// @author Venus Protocol
/// @notice Interface for the Venus Core Pool Comptroller (Diamond proxy) with e-mode pool support.
interface ICorePoolComptroller is IComptroller {
/// @notice Set collateral factor and liquidation threshold for a market in the core pool.
/// @param vToken The vToken market address.
/// @param newCollateralFactorMantissa The new collateral factor mantissa (scaled by 1e18).
/// @param newLiquidationThresholdMantissa The new liquidation threshold mantissa (scaled by 1e18).
/// @return uint256 Error code (0 = success).
function setCollateralFactor(
address vToken,
uint256 newCollateralFactorMantissa,
uint256 newLiquidationThresholdMantissa
) external returns (uint256);
/// @notice Set collateral factor and liquidation threshold for a market in a specific pool.
/// @param poolId The pool identifier (0 = core pool, >0 = e-mode pools).
/// @param vToken The vToken market address.
/// @param newCollateralFactorMantissa The new collateral factor mantissa (scaled by 1e18).
/// @param newLiquidationThresholdMantissa The new liquidation threshold mantissa (scaled by 1e18).
/// @return uint256 Error code (0 = success).
function setCollateralFactor(
uint96 poolId,
address vToken,
uint256 newCollateralFactorMantissa,
uint256 newLiquidationThresholdMantissa
) external returns (uint256);
/// @notice Remove a market from a specific pool.
/// @param poolId The pool identifier.
/// @param vToken The vToken market address to remove.
function removePoolMarket(uint96 poolId, address vToken) external;
/// @notice Pause or unpause flash loans globally.
/// @param paused True to pause, false to unpause.
function setFlashLoanPaused(bool paused) external;
/// @notice Returns whether flash loans are currently paused globally.
function flashLoanPaused() external view returns (bool);
/// @notice Enable or disable borrowing for a specific market in a specific pool.
/// @dev Independent from the global `_actionPaused[market][BORROW]` flag — both must
/// allow borrowing for borrows to actually proceed in a given pool/market.
/// @param poolId The pool identifier (0 = core pool, >0 = e-mode pools).
/// @param vToken The vToken market address.
/// @param borrowAllowed True to allow borrowing, false to disable it.
function setIsBorrowAllowed(uint96 poolId, address vToken, bool borrowAllowed) external;
/// @notice Add or remove an account from the flash loan whitelist.
/// @param account The account address.
/// @param isWhiteListed True to whitelist, false to revoke.
function setWhiteListFlashLoanAccount(address account, bool isWhiteListed) external;
/// @notice Returns whether an account is authorized for flash loans.
/// @param account The account address.
function authorizedFlashLoan(address account) external view returns (bool);
/// @notice Get the core pool identifier.
/// @return uint96 The core pool ID.
function corePoolId() external view returns (uint96);
/// @notice Get market data for a specific pool and vToken.
/// @param poolId The pool identifier.
/// @param vToken The vToken market address.
/// @return isListed Whether the market is listed in the pool.
/// @return collateralFactorMantissa The collateral factor mantissa.
/// @return isVenus Whether the market is a Venus market.
/// @return liquidationThresholdMantissa The liquidation threshold mantissa.
/// @return liquidationIncentiveMantissa The liquidation incentive mantissa.
/// @return marketPoolId The pool ID the market belongs to.
/// @return isBorrowAllowed Whether borrowing is allowed.
function poolMarkets(
uint96 poolId,
address vToken
)
external
view
returns (
bool isListed,
uint256 collateralFactorMantissa,
bool isVenus,
uint256 liquidationThresholdMantissa,
uint256 liquidationIncentiveMantissa,
uint96 marketPoolId,
bool isBorrowAllowed
);
/// @notice Get the last pool ID created.
/// @return uint96 The last pool ID.
function lastPoolId() external view returns (uint96);
}
contracts/Interfaces/IHubLiquidity.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.25;
/**
* @title IHubLiquidity
* @author Venus
* @notice Minimal views and emergency levers HubNavDeviationSentinel and EBrake need from the
* Liquidity Hub.
* @dev Hand-copied so this repo takes no dependency on liquidity-hub. Nothing cross-checks the
* selectors at build time, so a signature that drifts from the Hub's reverts on chain.
*/
interface IHub {
/// @notice Per-YieldGroup configuration held by the Hub's registry.
/// @param absoluteCap Hard cap on the YieldGroup's holdings, in asset units.
/// @param percentageCapBps Cap as a fraction of `totalAssets()`, in basis points.
/// @param paused When true, routing skips this YieldGroup; existing balance still counts.
/// @param registered True iff present in the Hub's YieldGroup registry.
struct YieldGroupConfig {
uint256 absoluteCap;
uint16 percentageCapBps;
bool paused;
bool registered;
}
/// @notice Pause the Hub, halting deposits and redemptions.
/// @dev ACM role `"pauseHub()"`. Idempotent — pausing an already-paused Hub is a silent no-op.
function pauseHub() external;
/// @notice Stop the Hub routing new deposits to a YieldGroup; its balance still counts toward NAV.
/// @dev ACM role `"pauseYieldGroup(address)"`. Idempotent, and reverts `YieldGroupNotRegistered`
/// for an address the Hub never registered.
/// @param yieldGroup YieldGroup to pause.
function pauseYieldGroup(address yieldGroup) external;
/// @notice Read a YieldGroup's registry entry.
/// @param yieldGroup YieldGroup to read.
/// @return config Stored configuration; all-zero when never registered.
function yieldGroupConfig(address yieldGroup) external view returns (YieldGroupConfig memory config);
/// @notice Whether the Hub is currently paused.
/// @return paused True while the Hub is paused.
function hubPaused() external view returns (bool paused);
}
/**
* @title IHubRegistry
* @author Venus
* @notice The chain-level Hub directory, as far as HubNavDeviationSentinel needs it.
* @dev One per chain, and only on chains that run a Liquidity Hub. Governance writes it, so it
* answers whether an address is a Hub Venus onboarded rather than one that claims to be.
*/
interface IHubRegistry {
/// @notice Whether an address is a registered Hub.
/// @param hub Address to check.
/// @return registered True iff the registry lists `hub`.
function isHub(address hub) external view returns (bool registered);
}
/**
* @title IYieldGroupNav
* @author Venus
* @notice The registry and NavGuard reads HubNavDeviationSentinel needs from a YieldGroup, and the
* resource pause EBrake forwards to it.
*/
interface IYieldGroupNav {
/// @notice A resource's NavGuard band, as stored by the YieldGroup.
/// @param anchor Value the two gaps are sized off.
/// @param centre Where the band sits: the anchor plus Venus's own deposits since.
/// @param anchoredAt When the band last re-anchored.
/// @param driftFrom When the drift clock last restarted.
/// @param interval Seconds between re-anchors; `0` means no band is configured.
/// @param driftBps Annual drift allowance, in basis points.
/// @param upGapBps How far above the centre the band reaches, in basis points of the anchor.
/// @param downGapBps How far below the centre the band reaches, in basis points of the anchor.
/// @param capEnabled Whether the Hub holds its valuation to the cap.
/// @param floorEnabled Whether the Hub holds its valuation to the floor.
struct NavBand {
uint128 anchor;
uint128 centre;
uint64 anchoredAt;
uint64 driftFrom;
uint32 interval;
uint16 driftBps;
uint16 upGapBps;
uint16 downGapBps;
bool capEnabled;
bool floorEnabled;
}
/// @notice The Hub this YieldGroup reports assets to.
/// @dev Written once in the YieldGroup's initializer, so HubNavDeviationSentinel can derive the Hub
/// from the YieldGroup instead of having a keeper name it.
/// @return hubAddress Hub that owns this YieldGroup.
function hub() external view returns (address hubAddress);
/// @notice Per-resource registration / pause state plus the adapter handling it.
/// @param resource Address to look up.
/// @return registered True iff present in the YieldGroup's resource registry.
/// @return paused True iff this resource is paused.
/// @return adapter `IResourceAdapter` implementation bound to this resource.
function resourceConfig(address resource) external view returns (bool registered, bool paused, address adapter);
/// @notice Stop the YieldGroup routing new deposits to a resource; its balance still counts
/// toward NAV, but user withdrawals skip it.
/// @dev ACM role `"pauseResource(address)"`, checked against this YieldGroup's address. Idempotent,
/// and reverts `ResourceNotRegistered` for an address the YieldGroup never registered.
/// @param resource Resource to pause.
function pauseResource(address resource) external;
/// @notice The band's own stored numbers for a resource.
/// @dev Field order must match the Hub's `NavBand` exactly. `anchor` and `centre` are both
/// `uint128` and adjacent, so a reordering there would decode silently wrong rather than
/// revert — pin this against `INavGuard.NavBand` when upgrading either side.
///
/// `centre` is the value as last saved, on a deposit, redeem or re-anchor. The Hub grows it
/// by `driftBps` a year since `driftFrom`, so a caller wanting the live centre must too.
/// @param resource Resource to look up.
/// @return band The stored band.
function navGuard(address resource) external view returns (NavBand memory band);
/// @notice Where a resource's value stands against its NavGuard band right now.
/// @dev Never reverts. A zero `observedValue` is ambiguous on purpose: the Hub reads the value
/// source as `(value, readable)` and drops the flag here, so a read that failed and a
/// position the counterparty prices at nothing arrive identically. The Hub values the
/// position at 0 in both cases, which is why HubNavDeviationSentinel pauses on either when
/// the band is open.
/// @param resource Resource to read.
/// @return observedValue Value the counterparty reports, in asset units; `0` if unreadable or genuinely zero.
/// @return minAllowedValue Lowest value the band allows right now.
/// @return maxAllowedValue Highest value the band allows right now.
/// @return isClamped Whether valuation is currently reporting a bound instead of `observedValue`.
/// @return clampedValue What valuation reports instead; `0` when `isClamped` is false.
function navGuardStatus(
address resource
)
external
view
returns (
uint256 observedValue,
uint256 minAllowedValue,
uint256 maxAllowedValue,
bool isClamped,
uint256 clampedValue
);
}
contracts/Interfaces/IILComptroller.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.25;
/**
* @title IILComptroller
* @notice Interface for Isolated Lending (IL) comptrollers.
* @dev IL comptrollers differ from the Diamond proxy: markets() returns a 3-value tuple
* and setCollateralFactor returns void instead of uint256.
*/
interface IILComptroller {
/// @notice Market metadata returned by the IL comptroller.
/// @param isListed Whether the market is listed.
/// @param collateralFactorMantissa The collateral factor (scaled by 1e18).
/// @param liquidationThresholdMantissa The liquidation threshold (scaled by 1e18).
struct Market {
bool isListed;
uint256 collateralFactorMantissa;
uint256 liquidationThresholdMantissa;
}
/// @notice Set the collateral factor and liquidation threshold for a market.
/// @param vToken The vToken market address.
/// @param newCollateralFactorMantissa The new collateral factor (scaled by 1e18).
/// @param newLiquidationThresholdMantissa The new liquidation threshold (scaled by 1e18).
function setCollateralFactor(
address vToken,
uint256 newCollateralFactorMantissa,
uint256 newLiquidationThresholdMantissa
) external;
/// @notice Get the market metadata for a vToken.
/// @param vToken The vToken market address.
/// @return market The market metadata.
function markets(address vToken) external view returns (Market memory market);
/// @notice Enter a market for an account. The caller needs the ACM permission for `enterMarketForAccount(address,address)`.
/// @param account The account to enter the market for.
/// @param vToken The vToken market address.
function enterMarketForAccount(address account, address vToken) external;
}
contracts/Interfaces/IVToken.sol
pragma solidity ^0.8.25;
import { IERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import { IComptroller } from "./IComptroller.sol";
interface IVToken is IERC20Upgradeable {
function accrueInterest() external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function borrowBalanceCurrent(address borrower) external returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
function mintBehalf(address receiver, uint mintAmount) external returns (uint);
function borrowBehalf(address borrower, uint borrowAmount) external returns (uint256);
function comptroller() external view returns (IComptroller);
function borrowBalanceStored(address account) external view returns (uint256);
function underlying() external view returns (address);
function totalBorrows() external view returns (uint256);
function totalBorrowsCurrent() external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function flashLoanFeeMantissa() external view returns (uint256);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint256);
function redeemUnderlyingBehalf(address redeemer, uint redeemAmount) external returns (uint);
function redeemBehalf(address redeemer, uint redeemTokens) external returns (uint);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"useLiteralContent": true
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.