Verified contractExactMIT
AgentHub
Address0x73d1bdcdb39ef06aea0371288a3ca5f1559ffcba
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.27
- Same code
Only this contract
Details
- Compiler
- solc 0.8.27+commit.40a35a09
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- shanghai
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 23,876,158
- Creation transaction
- 0xebcb22e823…87b70ee2f2
11 files
- src/contracts/AgentHub.solmain8.57 KB
- lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol4.03 KB
- lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol8.91 KB
- lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol1.19 KB
- lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol12.89 KB
- src/contracts/AgentConfigurator.sol13.64 KB
- src/contracts/dependencies/IRiskOracle.sol4.21 KB
- src/interfaces/IAgentConfigurator.sol20.59 KB
- src/interfaces/IAgentHub.sol1.33 KB
- src/interfaces/IBaseAgent.sol2.63 KB
src/contracts/AgentHub.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.27;
import {EnumerableSet} from 'openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol';
import {IRiskOracle} from './dependencies/IRiskOracle.sol';
import {IAgentHub} from '../interfaces/IAgentHub.sol';
import {IBaseAgent} from '../interfaces/IBaseAgent.sol';
import {AgentConfigurator} from './AgentConfigurator.sol';
/**
* @title AgentHub
* @author BGD Labs
* @notice Contract acting as an orchestrator of agents, defining the high-level logic of simulation,
* validation (both hub's and agents') and final injection of updates via agents
*/
contract AgentHub is AgentConfigurator, IAgentHub {
using EnumerableSet for EnumerableSet.AddressSet;
constructor() {
_disableInitializers();
}
function initialize(address agentHubOwner) external initializer {
__AgentConfigurator_init(agentHubOwner);
}
/// @inheritdoc IAgentHub
function check(
uint256[] memory agentIds
) public view virtual returns (bool, ActionData[] memory) {
ActionData[] memory actionData = new ActionData[](agentIds.length);
uint256 actionCount;
AgentHubStorage storage $ = _getStorage();
uint256 maxBatchSize = $.maxBatchSize;
uint256 batchSize; // total number of updates across all agents
for (uint256 i = 0; i < agentIds.length; i++) {
uint256 agentId = agentIds[i];
AgentConfig storage config = $.config[agentId];
BasicConfig memory basicConfig = config.basicConfig;
if (!basicConfig.isAgentEnabled) continue;
address[] memory markets = _getAgentMarkets(
config,
basicConfig.isMarketsFromAgentEnabled,
basicConfig.agentAddress,
agentId
);
if (markets.length == 0) continue;
IRiskOracle riskOracle = IRiskOracle(basicConfig.riskOracle);
string memory updateType = config.updateType;
address[] memory marketsToUpdate = new address[](markets.length);
uint256 marketsToUpdateCount;
for (uint256 j = 0; j < markets.length; j++) {
// The Risk Oracle is expected to revert if we query a non-existing update.
// In that case, we simply skip the market
try riskOracle.getLatestUpdateByParameterAndMarket(updateType, markets[j]) returns (
IRiskOracle.RiskParameterUpdate memory updateRiskParams
) {
if (_validateBasics(config, basicConfig, agentId, updateRiskParams)) {
marketsToUpdate[marketsToUpdateCount++] = updateRiskParams.market;
batchSize++;
}
} catch {}
// stop collecting data if we reached max batch size, to protect against gas overflow on execution
if (maxBatchSize != 0 && batchSize == maxBatchSize) break;
}
if (marketsToUpdateCount != 0) {
assembly {
mstore(marketsToUpdate, marketsToUpdateCount)
}
actionData[actionCount].agentId = agentId;
actionData[actionCount].markets = marketsToUpdate;
actionCount++;
}
// stop collecting data if we reached max batch size, to protect against gas overflow on execution
if (maxBatchSize != 0 && batchSize == maxBatchSize) break;
}
assembly {
mstore(actionData, actionCount)
}
return (actionCount != 0, actionData);
}
/// @inheritdoc IAgentHub
function execute(ActionData[] memory actionData) public virtual {
AgentHubStorage storage $ = _getStorage();
bool hasValidActions;
for (uint256 i = 0; i < actionData.length; i++) {
uint256 agentId = actionData[i].agentId;
address[] memory markets = actionData[i].markets;
AgentConfig storage config = $.config[agentId];
BasicConfig memory basicConfig = config.basicConfig;
// skip if agent is disabled or user is not authorized
if (
!basicConfig.isAgentEnabled ||
(basicConfig.isAgentPermissioned && !config.permissionedSenders.contains(_msgSender()))
) continue;
string memory updateType = config.updateType;
address[] memory configuredMarkets = _getAgentMarkets(
config,
basicConfig.isMarketsFromAgentEnabled,
basicConfig.agentAddress,
agentId
);
for (uint256 j = 0; j < markets.length; j++) {
// The Risk Oracle is expected to revert if we query a non-existing update.
// In that case, we simply skip the market
try
IRiskOracle(basicConfig.riskOracle).getLatestUpdateByParameterAndMarket(
updateType,
markets[j]
)
returns (IRiskOracle.RiskParameterUpdate memory update) {
if (
_validateBasics(config, basicConfig, agentId, update) &&
// checks that the market from update corresponds to the configured markets on the agent
_isMarketConfigured(configuredMarkets, update.market)
) {
_setUpdateInjected(
config,
agentId,
update.market,
updateType,
update.updateId,
update.newValue
);
IBaseAgent(basicConfig.agentAddress).inject(agentId, basicConfig.agentContext, update);
hasValidActions = true;
}
} catch {}
}
}
require(hasValidActions, NoActionCanBePerformed());
}
/**
* @notice method to fetch markets for the corresponding agent
* @param config the config of the agent
* @param isMarketsFromAgentEnabled true if markets should be fetched from the agent,
* false if allowedMarkets should be taken from the Hub configuration
* @param agentAddress the agent address
* @param agentId the agentId
* @return list of markets corresponding to the agentId
*/
function _getAgentMarkets(
AgentConfig storage config,
bool isMarketsFromAgentEnabled,
address agentAddress,
uint256 agentId
) internal view returns (address[] memory) {
// Case we fetch only allowed markets configured on the Hub for this Agent
if (!isMarketsFromAgentEnabled) {
return config.allowedMarkets.values();
}
// Otherwise we fetch all markets from the Agent and apply the configured restricted markets
address[] memory markets = IBaseAgent(agentAddress).getMarkets(agentId);
if (config.restrictedMarkets.length() == 0) return markets;
uint256 validMarketCount;
address[] memory validMarkets = new address[](markets.length);
for (uint256 i = 0; i < markets.length; i++) {
if (!config.restrictedMarkets.contains(markets[i])) {
validMarkets[validMarketCount++] = markets[i];
}
}
assembly {
mstore(validMarkets, validMarketCount)
}
return validMarkets;
}
/**
* @notice method to do generic and agent specific validation for an update
* @param config the config of the agent
* @param basicConfig the basic config of the agent
* @param agentId the agentId for the agent for which to validate the update
* @param update the risk oracle update to validate
* @return true if the generic and agent specific validation passes for an update
*/
function _validateBasics(
AgentConfig storage config,
BasicConfig memory basicConfig,
uint256 agentId,
IRiskOracle.RiskParameterUpdate memory update
) internal view returns (bool) {
// validates if the update is not expired
if (update.timestamp + basicConfig.expirationPeriod < block.timestamp) return false;
LastInjectedUpdate memory lastInjectedUpdate = config.lastInjectedUpdate[update.market];
// validates if the updateId is not executed before
if (lastInjectedUpdate.id >= update.updateId) return false;
// validates if minimum delay has passed since the last update for an agent and market
if (block.timestamp - lastInjectedUpdate.timestamp < basicConfig.minimumDelay) return false;
// agent specific validation
return IBaseAgent(basicConfig.agentAddress).validate(agentId, basicConfig.agentContext, update);
}
/**
* @notice method to check that address included into the array
* @param configuredMarkets the list of configured markets for the agent
* @param market the address to check
* @return true if market was configured, false otherwise
*/
function _isMarketConfigured(
address[] memory configuredMarkets,
address market
) internal pure returns (bool) {
for (uint256 i = 0; i < configuredMarkets.length; i++) {
if (configuredMarkets[i] == market) {
return true;
}
}
return false;
}
}
lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../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.
*
* The initial owner is set to the address provided by the deployer. 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 {
/// @custom:storage-location erc7201:openzeppelin.storage.Ownable
struct OwnableStorage {
address _owner;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;
function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
assembly {
$.slot := OwnableStorageLocation
}
}
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
function __Ownable_init(address initialOwner) internal onlyInitializing {
__Ownable_init_unchained(initialOwner);
}
function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @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) {
OwnableStorage storage $ = _getOwnableStorage();
return $._owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @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 {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
OwnableStorage storage $ = _getOwnableStorage();
address oldOwner = $._owner;
$._owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @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 Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 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 in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._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 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._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() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @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 {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
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;
}
}
lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
}
src/contracts/AgentConfigurator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.27;
import {SafeCast} from 'openzeppelin-contracts/contracts/utils/math/SafeCast.sol';
import {OwnableUpgradeable} from 'openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol';
import {EnumerableSet} from 'openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol';
import {IAgentConfigurator} from '../interfaces/IAgentConfigurator.sol';
/**
* @title AgentConfigurator
* @author BGD Labs
* @notice Contract to manage configurations for the AgentHub.
*/
abstract contract AgentConfigurator is OwnableUpgradeable, IAgentConfigurator {
using SafeCast for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
/**
* @custom:storage-location erc7201:agent.storage.hub
*/
struct AgentHubStorage {
/// @notice the total number of agents registered for this hub
uint240 agentCount;
/// @notice the max batch size for the hub, used as soft measure to prevent exceeding the gas limit
uint16 maxBatchSize;
/// @notice map of agent specific configuration
mapping(uint256 agentId => AgentConfig) config;
}
/**
* @notice Struct storing the agent configurations
*/
struct AgentConfig {
/// @notice map of last injected update including updateId and timestamp for the market
mapping(address market => LastInjectedUpdate) lastInjectedUpdate;
/// @notice enumerable set of allowed markets, used only when isMarketsFromAgentEnabled is false
EnumerableSet.AddressSet allowedMarkets;
/// @notice enumerable set of restricted markets, used only when isMarketsFromAgentEnabled is true
EnumerableSet.AddressSet restrictedMarkets;
/// @notice enumerable set of permissioned senders allowed to call `execute()` for the agent
EnumerableSet.AddressSet permissionedSenders;
/// @notice address of the admin of the agent, which can update configurations
address admin;
/// @notice the update type string for the agent
string updateType;
/// @notice struct storing basic config for the agent, packed tightly to reduce sloads
BasicConfig basicConfig;
}
/**
* @notice Struct storing the basic agent configurations
*/
struct BasicConfig {
/// @notice address of the chaos risk-oracle used by the agent
address riskOracle;
/// @notice bool storing if the agent is enabled or not
bool isAgentEnabled;
/// @notice bool storing if the agent is permissioned or not
bool isAgentPermissioned;
/// @notice bool storing if to fetch configured markets from agent
bool isMarketsFromAgentEnabled;
/// @notice address of the agent contract which is used to do agent specific validation and injection
address agentAddress;
/// @notice expiration period for the update of the agent in seconds
uint32 expirationPeriod;
/// @notice minimum delay configured for the agent in seconds
uint32 minimumDelay;
/// @notice stores misc config for the agent, typically used during agent validation and injection
bytes agentContext;
}
// keccak256(abi.encode(uint256(keccak256('agent.storage.hub')) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AGENT_HUB_STORAGE_LOCATION =
0xa6a8e78397042a5280bd150d020dc296a49efd5c4cfc37400f38cd94c9ec6400;
/**
* @notice method to get the storage pointer for the AgentHub as per EIP 7201
* @return $ storage pointer of the AgentHub contract
*/
function _getStorage() internal pure returns (AgentHubStorage storage $) {
assembly {
$.slot := AGENT_HUB_STORAGE_LOCATION
}
}
function __AgentConfigurator_init(address agentHubOwner) internal onlyInitializing {
__Ownable_init(agentHubOwner);
}
modifier onlyOwnerOrAgentAdmin(uint256 agentId) {
require(
owner() == _msgSender() || getAgentAdmin(agentId) == _msgSender(),
OnlyOwnerOrAgentAdmin(_msgSender())
);
_;
}
/// @inheritdoc IAgentConfigurator
function registerAgent(
AgentRegistrationInput calldata input
) external onlyOwner returns (uint256) {
AgentHubStorage storage $ = _getStorage();
uint256 agentId = $.agentCount++;
AgentConfig storage config = $.config[agentId];
// basic agent registration
config.updateType = input.updateType;
config.basicConfig.riskOracle = input.riskOracle;
emit AgentRegistered(agentId, input.riskOracle, config.updateType);
// agent configuration
setAgentAddress(agentId, input.agentAddress);
setAgentAdmin(agentId, input.admin);
setAgentEnabled(agentId, input.isAgentEnabled);
setAgentAsPermissioned(agentId, input.isAgentPermissioned);
setMarketsFromAgentEnabled(agentId, input.isMarketsFromAgentEnabled);
setExpirationPeriod(agentId, input.expirationPeriod);
setMinimumDelay(agentId, input.minimumDelay);
setAgentContext(agentId, input.agentContext);
// configure markets on agent
for (uint256 i = 0; i < input.allowedMarkets.length; i++) {
addAllowedMarket(agentId, input.allowedMarkets[i]);
}
for (uint256 i = 0; i < input.restrictedMarkets.length; i++) {
addRestrictedMarket(agentId, input.restrictedMarkets[i]);
}
for (uint256 i = 0; i < input.permissionedSenders.length; i++) {
addPermissionedSender(agentId, input.permissionedSenders[i]);
}
return agentId;
}
/// @inheritdoc IAgentConfigurator
function setAgentAdmin(uint256 agentId, address admin) public onlyOwner {
require(admin != address(this) && admin != getAgentAddress(agentId), InvalidAgentAdmin(admin));
_getStorage().config[agentId].admin = admin;
emit AgentAdminSet(agentId, admin);
}
/// @inheritdoc IAgentConfigurator
function setMaxBatchSize(uint256 maxBatchSize) external onlyOwner {
_getStorage().maxBatchSize = maxBatchSize.toUint16();
emit MaxBatchSizeSet(maxBatchSize);
}
/// @inheritdoc IAgentConfigurator
function setAgentAddress(uint256 agentId, address agentAddress) public onlyOwner {
_getStorage().config[agentId].basicConfig.agentAddress = agentAddress;
emit AgentAddressSet(agentId, agentAddress);
}
/// @inheritdoc IAgentConfigurator
function setAgentAsPermissioned(
uint256 agentId,
bool permissioned
) public onlyOwnerOrAgentAdmin(agentId) {
_getStorage().config[agentId].basicConfig.isAgentPermissioned = permissioned;
emit AgentPermissionedStatusSet(agentId, permissioned);
}
/// @inheritdoc IAgentConfigurator
function addPermissionedSender(
uint256 agentId,
address sender
) public onlyOwnerOrAgentAdmin(agentId) {
bool success = _getStorage().config[agentId].permissionedSenders.add(sender);
if (success) emit PermissionedSenderAdded(agentId, sender);
}
/// @inheritdoc IAgentConfigurator
function removePermissionedSender(
uint256 agentId,
address sender
) external onlyOwnerOrAgentAdmin(agentId) {
bool success = _getStorage().config[agentId].permissionedSenders.remove(sender);
if (success) emit PermissionedSenderRemoved(agentId, sender);
}
/// @inheritdoc IAgentConfigurator
function addAllowedMarket(uint256 agentId, address market) public onlyOwnerOrAgentAdmin(agentId) {
bool success = _getStorage().config[agentId].allowedMarkets.add(market);
if (success) emit AllowedMarketAdded(agentId, market);
}
/// @inheritdoc IAgentConfigurator
function removeAllowedMarket(
uint256 agentId,
address market
) public onlyOwnerOrAgentAdmin(agentId) {
bool success = _getStorage().config[agentId].allowedMarkets.remove(market);
if (success) emit AllowedMarketRemoved(agentId, market);
}
/// @inheritdoc IAgentConfigurator
function addRestrictedMarket(
uint256 agentId,
address market
) public onlyOwnerOrAgentAdmin(agentId) {
bool success = _getStorage().config[agentId].restrictedMarkets.add(market);
if (success) emit RestrictedMarketAdded(agentId, market);
}
/// @inheritdoc IAgentConfigurator
function removeRestrictedMarket(
uint256 agentId,
address market
) external onlyOwnerOrAgentAdmin(agentId) {
bool success = _getStorage().config[agentId].restrictedMarkets.remove(market);
if (success) emit RestrictedMarketRemoved(agentId, market);
}
/// @inheritdoc IAgentConfigurator
function setExpirationPeriod(
uint256 agentId,
uint256 expirationPeriod
) public onlyOwnerOrAgentAdmin(agentId) {
_getStorage().config[agentId].basicConfig.expirationPeriod = expirationPeriod.toUint32();
emit ExpirationPeriodSet(agentId, expirationPeriod);
}
/// @inheritdoc IAgentConfigurator
function setAgentEnabled(uint256 agentId, bool enable) public onlyOwnerOrAgentAdmin(agentId) {
_getStorage().config[agentId].basicConfig.isAgentEnabled = enable;
emit AgentEnabledSet(agentId, enable);
}
/// @inheritdoc IAgentConfigurator
function setMinimumDelay(
uint256 agentId,
uint256 minimumDelay
) public onlyOwnerOrAgentAdmin(agentId) {
_getStorage().config[agentId].basicConfig.minimumDelay = minimumDelay.toUint32();
emit MinimumDelaySet(agentId, minimumDelay);
}
/// @inheritdoc IAgentConfigurator
function setAgentContext(
uint256 agentId,
bytes calldata context
) public onlyOwnerOrAgentAdmin(agentId) {
_getStorage().config[agentId].basicConfig.agentContext = context;
emit AgentContextSet(agentId, context);
}
/// @inheritdoc IAgentConfigurator
function setMarketsFromAgentEnabled(
uint256 agentId,
bool enabled
) public onlyOwnerOrAgentAdmin(agentId) {
_getStorage().config[agentId].basicConfig.isMarketsFromAgentEnabled = enabled;
emit MarketsFromAgentEnabled(agentId, enabled);
}
/// @inheritdoc IAgentConfigurator
function getAgentAdmin(uint256 agentId) public view returns (address) {
return _getStorage().config[agentId].admin;
}
/// @inheritdoc IAgentConfigurator
function getMaxBatchSize() external view returns (uint256) {
return _getStorage().maxBatchSize;
}
/// @inheritdoc IAgentConfigurator
function getAgentAddress(uint256 agentId) public view returns (address) {
return _getStorage().config[agentId].basicConfig.agentAddress;
}
/// @inheritdoc IAgentConfigurator
function isAgentPermissioned(uint256 agentId) external view returns (bool) {
return _getStorage().config[agentId].basicConfig.isAgentPermissioned;
}
/// @inheritdoc IAgentConfigurator
function getPermissionedSenders(uint256 agentId) external view returns (address[] memory) {
return _getStorage().config[agentId].permissionedSenders.values();
}
/// @inheritdoc IAgentConfigurator
function isPermissionedSender(uint256 agentId, address sender) external view returns (bool) {
return _getStorage().config[agentId].permissionedSenders.contains(sender);
}
/// @inheritdoc IAgentConfigurator
function getAllowedMarkets(uint256 agentId) external view returns (address[] memory) {
return _getStorage().config[agentId].allowedMarkets.values();
}
/// @inheritdoc IAgentConfigurator
function getRestrictedMarkets(uint256 agentId) external view returns (address[] memory) {
return _getStorage().config[agentId].restrictedMarkets.values();
}
/// @inheritdoc IAgentConfigurator
function getExpirationPeriod(uint256 agentId) external view returns (uint256) {
return _getStorage().config[agentId].basicConfig.expirationPeriod;
}
/// @inheritdoc IAgentConfigurator
function isAgentEnabled(uint256 agentId) external view returns (bool) {
return _getStorage().config[agentId].basicConfig.isAgentEnabled;
}
/// @inheritdoc IAgentConfigurator
function getMinimumDelay(uint256 agentId) external view returns (uint256) {
return _getStorage().config[agentId].basicConfig.minimumDelay;
}
/// @inheritdoc IAgentConfigurator
function getAgentContext(uint256 agentId) external view returns (bytes memory) {
return _getStorage().config[agentId].basicConfig.agentContext;
}
/// @inheritdoc IAgentConfigurator
function isMarketsFromAgentEnabled(uint256 agentId) external view returns (bool) {
return _getStorage().config[agentId].basicConfig.isMarketsFromAgentEnabled;
}
/// @inheritdoc IAgentConfigurator
function getUpdateType(uint256 agentId) external view returns (string memory) {
return _getStorage().config[agentId].updateType;
}
/// @inheritdoc IAgentConfigurator
function getRiskOracle(uint256 agentId) external view returns (address) {
return _getStorage().config[agentId].basicConfig.riskOracle;
}
/// @inheritdoc IAgentConfigurator
function getAgentCount() external view returns (uint256) {
return _getStorage().agentCount;
}
/// @inheritdoc IAgentConfigurator
function getLastInjectedUpdate(
uint256 agentId,
address market
) external view returns (LastInjectedUpdate memory) {
return _getStorage().config[agentId].lastInjectedUpdate[market];
}
/**
* @notice method to mark an update for a market as injected
* @param config the config of the agent
* @param market the address of the market to update parameters
* @param updateType the update type to execute
* @param updateId the updateId corresponding to the update
* @param newValue the new value of parameters
*/
function _setUpdateInjected(
AgentConfig storage config,
uint256 agentId,
address market,
string memory updateType,
uint256 updateId,
bytes memory newValue
) internal {
config.lastInjectedUpdate[market] = LastInjectedUpdate({
timestamp: block.timestamp.toUint48(),
id: updateId.toUint208()
});
emit UpdateInjected(agentId, market, updateType, updateId, newValue);
}
}
src/contracts/dependencies/IRiskOracle.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IRiskOracle {
struct RiskParameterUpdate {
uint256 timestamp; // Timestamp of the update
bytes newValue; // Encoded parameters, flexible for various data types
string referenceId; // External reference, potentially linking to a document or off-chain data
bytes previousValue; // Previous value of the parameter for historical comparison
string updateType; // Classification of the update for validation purposes
uint256 updateId; // Unique identifier for this specific update
address market; // Address for market of the parameter update
bytes additionalData; // Additional data for the update
}
event ParameterUpdated(
string referenceId,
bytes newValue,
bytes previousValue,
uint256 timestamp,
string indexed updateType,
uint256 indexed updateId,
address indexed market,
bytes additionalData
);
event AuthorizedSenderAdded(address indexed sender);
event AuthorizedSenderRemoved(address indexed sender);
event UpdateTypeAdded(string indexed updateType);
/**
* @notice Adds a new sender to the list of addresses authorized to perform updates.
* @param sender Address to be authorized.
*/
function addAuthorizedSender(address sender) external;
/**
* @notice Removes an address from the list of authorized senders.
* @param sender Address to be unauthorized.
*/
function removeAuthorizedSender(address sender) external;
/**
* @notice Method to fetch the counter which tracks of the total number of updates.
* @return The latest update counter.
*/
function updateCounter() external view returns (uint256);
/**
* @notice Adds a new type of update to the list of authorized update types.
* @param newUpdateType New type of update to allow.
*/
function addUpdateType(string memory newUpdateType) external;
/**
* @notice Publishes a new risk parameter update.
* @param referenceId An external reference ID associated with the update.
* @param newValue The new value of the risk parameter being updated.
* @param updateType Type of update performed, must be previously authorized.
* @param market Address for market of the parameter update
* @param additionalData Additional data for the update
*/
function publishRiskParameterUpdate(
string memory referenceId,
bytes memory newValue,
string memory updateType,
address market,
bytes memory additionalData
) external;
/**
* @notice Publishes multiple risk parameter updates in a single transaction.
* @param referenceIds Array of external reference IDs.
* @param newValues Array of new values for each update.
* @param updateTypes Array of types for each update, all must be authorized.
* @param markets Array of addresses for markets of the parameter updates
* @param additionalData Array of additional data for the updates
*
*/
function publishBulkRiskParameterUpdates(
string[] memory referenceIds,
bytes[] memory newValues,
string[] memory updateTypes,
address[] memory markets,
bytes[] memory additionalData
) external;
function getAllUpdateTypes() external view returns (string[] memory);
/**
* @notice Fetches the most recent update for a specific parameter in a specific market.
* @param updateType The identifier for the parameter.
* @param market The market identifier.
* @return The most recent RiskParameterUpdate for the specified parameter and market.
*/
function getLatestUpdateByParameterAndMarket(
string memory updateType,
address market
) external view returns (RiskParameterUpdate memory);
/*
* @notice Fetches the update for a provided updateId.
* @param updateId Update ID.
* @return The most recent RiskParameterUpdate for the specified id.
*/
function getUpdateById(uint256 updateId) external view returns (RiskParameterUpdate memory);
/**
* @notice Checks if an address is authorized to perform updates.
* @param sender Address to check.
* @return Boolean indicating whether the address is authorized.
*/
function isAuthorized(address sender) external view returns (bool);
}
src/interfaces/IAgentConfigurator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title IAgentConfigurator
* @author BGD labs
* @notice Defines the interface for the AgentConfigurator contract
*/
interface IAgentConfigurator {
/**
* @notice The caller account is not the owner or agent admin
*/
error OnlyOwnerOrAgentAdmin(address account);
/**
* @notice Cannot set the hub address or agent contract address as agent admin
*/
error InvalidAgentAdmin(address agentAdmin);
/**
* @notice Struct storing the agent registration input when registering the agent
*/
struct AgentRegistrationInput {
address admin;
address riskOracle;
bool isAgentEnabled;
bool isAgentPermissioned;
bool isMarketsFromAgentEnabled;
address agentAddress;
uint256 expirationPeriod;
uint256 minimumDelay;
string updateType;
bytes agentContext;
address[] allowedMarkets;
address[] restrictedMarkets;
address[] permissionedSenders;
}
/**
* @notice Struct storing the last injected update for an agent-market pair
*/
struct LastInjectedUpdate {
uint48 timestamp;
uint208 id;
}
/**
* @notice Emitted when an updateId is injected from the risk oracle
* @param agentId the id of the agent for which the update was injected
* @param market the market address where update was injected
* @param updateType the type of the update which was injected
* @param updateId the id of the update corresponding to the risk oracle
* @param newValue the new value fetched from the risk oracle which is injected
*/
event UpdateInjected(
uint256 indexed agentId,
address indexed market,
string indexed updateType,
uint256 updateId,
bytes newValue
);
/**
* @notice Emitted when the owner registers a new agent
* @param agentId the id of the new agent registered
* @param riskOracle the address of the risk oracle to consume updates
* @param updateType the string reference of the updates which will be consumed
*/
event AgentRegistered(
uint256 indexed agentId,
address indexed riskOracle,
string indexed updateType
);
/**
* @notice Emitted when the owner sets agent admin for an agent
* @param agentId the id of the agent for which new agent admin is set
* @param admin the address of the new admin set for the agent
*/
event AgentAdminSet(uint256 indexed agentId, address indexed admin);
/**
* @notice Emitted when the owner sets the max batch size
* @param maxBatchSize the max batch size of updates set for injection across all agent in one `execute()` call
*/
event MaxBatchSizeSet(uint256 indexed maxBatchSize);
/**
* @notice Emitted when the agent admin sets a agent contract for an agent
* @param agentId the id of the agent for which the agent contract is set
* @param agentAddress the address of the agent contract set
*/
event AgentAddressSet(uint256 indexed agentId, address indexed agentAddress);
/**
* @notice Emitted when the agent admin sets the permissioned status for the agent
* @param agentId the id of the agent for which the permissioned status is set
* @param isAgentPermissioned true if the agent is permissioned, false otherwise
*/
event AgentPermissionedStatusSet(uint256 indexed agentId, bool indexed isAgentPermissioned);
/**
* @notice Emitted when the agent admin adds a permissioned sender
* @param agentId the id of the agent for which permissioned sender is added
* @param sender address of the sender which is permissioned for the agent
*/
event PermissionedSenderAdded(uint256 indexed agentId, address indexed sender);
/**
* @notice Emitted when the agent admin removes a permissioned sender
* @param agentId the id of the agent for which permissioned sender is removed
* @param sender address of the sender for which permissioned sender is removed for the agent
*/
event PermissionedSenderRemoved(uint256 indexed agentId, address indexed sender);
/**
* @notice Emitted when the agent admin adds a allowed market for the agent
* @param agentId the id of the agent for which the allowed market is added
* @param market the address of the allowed market added
*/
event AllowedMarketAdded(uint256 indexed agentId, address indexed market);
/**
* @notice Emitted when the agent admin removes a allowed market for the agent
* @param agentId the id of the agent for which the allowed market is removed
* @param market the address of the allowed market removed
*/
event AllowedMarketRemoved(uint256 indexed agentId, address indexed market);
/**
* @notice Emitted when the agent admin adds a restricted market for the agent
* @param agentId the id of the agent for which the restricted market is added
* @param market the address of the restricted market added
*/
event RestrictedMarketAdded(uint256 indexed agentId, address indexed market);
/**
* @notice Emitted when the agent admin removes a restricted market for the agent
* @param agentId the id of the agent for which the restricted market is removed
* @param market the address of the restricted market removed
*/
event RestrictedMarketRemoved(uint256 indexed agentId, address indexed market);
/**
* @notice Emitted when the agent admin sets the expiration period of the agent
* @param agentId the id of the agent for which expiration period is set
* @param expirationPeriod the expiration period set
*/
event ExpirationPeriodSet(uint256 indexed agentId, uint256 indexed expirationPeriod);
/**
* @notice Emitted when the agent admin sets the enable status for the agent
* @param agentId the id of the agent for which enable status is set
* @param enable true if the agent is set as enabled, false otherwise
*/
event AgentEnabledSet(uint256 indexed agentId, bool indexed enable);
/**
* @notice Emitted when the agent admin sets the minimum delay of the agent
* @param agentId the id of the agent for which minimum delay is set
* @param minimumDelay the minimum delay set
*/
event MinimumDelaySet(uint256 indexed agentId, uint256 indexed minimumDelay);
/**
* @notice Emitted when the agent admin sets the agent context of the agent
* @param agentId the id of the agent for which agent context is set
* @param context the context set for the agent in bytes
*/
event AgentContextSet(uint256 indexed agentId, bytes indexed context);
/**
* @notice Emitted when the agent admin sets isMarketsFromAgentEnabled flag
* @param agentId the id of the agent for which isMarketsFromAgentEnabled flag is set
* @param enabled true if flag set to fetch markets from the agent contract, false if to fetch from the hub
*/
event MarketsFromAgentEnabled(uint256 indexed agentId, bool indexed enabled);
/**
* @notice method called by the owner to register a new agent
* @param registrationInput the initial configuration for the agent to register
* @return agentId the id for the agent registered
*/
function registerAgent(
AgentRegistrationInput calldata registrationInput
) external returns (uint256);
/**
* @notice method called by the admin address to set a new agent admin address
* @param agentId the id of the agent for which to set the admin address
* @param admin the address of the new agent admin to set
*/
function setAgentAdmin(uint256 agentId, address admin) external;
/**
* @notice method called by the owner to set the max batch size for injection across all agents in one `execute()` call
* @param maxBatchSize the max batch size of updates for injection across all agents in one `execute()` call
* @dev the max batch size is enforced on the `check()` as a soft measure to ensure only the
* max batch size number of updates gets injected in one `execute()` call
* max batch size of 0 denotes max batch size enforcement is disabled i.e all valid updates will be injected in one `execute()`
*/
function setMaxBatchSize(uint256 maxBatchSize) external;
/**
* @notice method called by the owner to set the agent contract address
* @param agentId the id of the agent for which the agent contract is set
* @param agentAddress the address of the agent contract to set which does postValidation and injection
*/
function setAgentAddress(uint256 agentId, address agentAddress) external;
/**
* @notice method called by the agent admin to set if the agent is permissioned or not
* @param agentId the id of the agent to set the permissioned status
* @param isAgentPermissioned true if the agent is permissioned, false otherwise
*/
function setAgentAsPermissioned(uint256 agentId, bool isAgentPermissioned) external;
/**
* @notice method called by the agent admin to add permissioned sender
* @param agentId the id of the agent for which to add permissioned sender
* @param sender address of the sender to allow calling `execute()` for the agent
*/
function addPermissionedSender(uint256 agentId, address sender) external;
/**
* @notice method called by the agent admin to remove permissioned sender
* @param agentId the id of the agent for which to remove permissioned sender
* @param sender address of the sender to remove from calling `execute()` for the agent
*/
function removePermissionedSender(uint256 agentId, address sender) external;
/**
* @notice method called by the agent admin to add allowed market for the agent
* @param agentId the id of the agent for which to add allowed market
* @param market the address of the allowed market to add
* @dev if isMarketsFromAgentEnabled config is false, configured markets for the agent
* will be the allowed markets from hub and restricted markets will be ignored.
*/
function addAllowedMarket(uint256 agentId, address market) external;
/**
* @notice method called by the agent admin to remove allowed market for the agent
* @param agentId the id of the agent for which to remove allowed market
* @param market the address of the allowed to remove
* @dev if isMarketsFromAgentEnabled config is false, configured markets for the agent
* will be the allowed markets from hub and restricted markets will be ignored.
*/
function removeAllowedMarket(uint256 agentId, address market) external;
/**
* @notice method called by the agent admin to add restricted market for the agent
* @param agentId the id of the agent for which to add restricted market
* @param market the address of the restricted market to add
* @dev if isMarketsFromAgentEnabled config is true, configured markets for that agent
* will be fetched from the agent contract and filtered by the restricted markets,
* allowed markets in this case will be unused and ignored
*/
function addRestrictedMarket(uint256 agentId, address market) external;
/**
* @notice method called by the agent admin to remove restricted market for the agent
* @param agentId the id of the agent for which to remove restricted market
* @param market the address of the restricted market to remove
* @dev if isMarketsFromAgentEnabled config is true, configured markets for that agent
* will be fetched from the agent contract and filtered by the restricted markets,
* allowed markets in this case will be unused and ignored
*/
function removeRestrictedMarket(uint256 agentId, address market) external;
/**
* @notice method called by the agent admin to set the expiration period for the agent
* @param agentId the id of the agent to set expiration period
* @param expirationPeriod expiration period of the agent to set in seconds
*/
function setExpirationPeriod(uint256 agentId, uint256 expirationPeriod) external;
/**
* @notice method called by the agent admin to set the enabled status for the agent
* @param agentId the id of the agent to set enabled status
* @param enable true if the agent is set as enabled, false otherwise
*/
function setAgentEnabled(uint256 agentId, bool enable) external;
/**
* @notice method called by the agent admin to set the minimum delay for the agent
* @param agentId the id of the agent to set minimum delay
* @param minimumDelay minimum delay of the agent to set in seconds
*/
function setMinimumDelay(uint256 agentId, uint256 minimumDelay) external;
/**
* @notice method to set the agent context
* agent context could be used to store injection/validation configuration which used by the agent contract
* @param agentId the id of the agent for which to set the agent context
* @param context the agent context to set for the agent in bytes
*/
function setAgentContext(uint256 agentId, bytes calldata context) external;
/**
* @notice method to set if markets used for injection should be fetched from the agent contract or hub
* @param agentId the id of the agent for which to set the isMarketsFromAgentEnabled flag
* @param enabled true if configured markets should be fetched from the agent, false if it should be fetched from the hub
* @dev if isMarketsFromAgentEnabled is false, the markets to fetch for injection is queried from the hub via allowedMarkets,
* if isMarketsFromAgentEnabled is true, the markets to fetch for injection is queried from the agent contract
* please note allowedMarkets is only used when isMarketsFromAgentEnabled is set to false, and restrictedMarkets
* is only applied when isMarketsFromAgentEnabled is true to filter out the markets from agent
*/
function setMarketsFromAgentEnabled(uint256 agentId, bool enabled) external;
/**
* @notice method to get the admin address for an agent which can configure params
* @param agentId the id of the agent for which to get the admin address
* @return address of the agent admin
*/
function getAgentAdmin(uint256 agentId) external view returns (address);
/**
* @notice method to get the max batch size for injection across all agent in one `execute()` call
* @return the max batch size of updates for injection across all agents in one `execute()` call
* @dev the max batch size is enforced on the `check()` as a soft measure to ensure only the
* max batch size number of updates gets injected in one `execute()` call
* max batch size of 0 denotes max batch size enforcement is disabled i.e all valid updates will be injected in one `execute()`
*/
function getMaxBatchSize() external view returns (uint256);
/**
* @notice method to get the configured agent contract address
* @param agentId the id of the agent to get the configured agent contract
* @return address of the agent contract
*/
function getAgentAddress(uint256 agentId) external view returns (address);
/**
* @notice method to get if the agent is permissioned or not
* @param agentId the id of the agent to get the permissioned status
* @return true if the agent is permissioned, false otherwise
*/
function isAgentPermissioned(uint256 agentId) external view returns (bool);
/**
* @notice method to get the permissioned senders for the agents, only valid if the agent is permissioned
* @param agentId the id of the agent to get the permissioned senders
* @return list of addresses of the permissioned senders for the agent
*/
function getPermissionedSenders(uint256 agentId) external view returns (address[] memory);
/**
* @notice method to get if the sender is allowed for the agent, only valid if the agent is permissioned
* @param agentId the id of the agent to check if the sender is allowed
* @return true if the sender is allowed, false otherwise
*/
function isPermissionedSender(uint256 agentId, address sender) external view returns (bool);
/**
* @notice method to get the list of allowed markets for the agent
* @param agentId the id of the agent to get the allowed markets
* @return list of allowed market addresses for the agent
* @dev if isMarketsFromAgentEnabled config is false, configured markets for the agent
* will be the allowed markets from hub and restricted markets will be ignored.
*/
function getAllowedMarkets(uint256 agentId) external view returns (address[] memory);
/**
* @notice method to get the list of restricted markets for the agent
* @param agentId the id of the agent to get the restricted markets
* @return list of restricted market addresses for the agent
* @dev if isMarketsFromAgentEnabled config is true, configured markets for that agent
* will be fetched from the agent contract and filtered by the restricted markets,
* allowed markets in this case will be unused and ignored
*/
function getRestrictedMarkets(uint256 agentId) external view returns (address[] memory);
/**
* @notice method to get the expiration period for the agent
* expiration period is the time in seconds since update was added on risk oracle
* within which update can be injected
* @param agentId the id of the agent to get expiration period
* @return expiration period of the agent in seconds
*/
function getExpirationPeriod(uint256 agentId) external view returns (uint256);
/**
* @notice method to get if the agent is enabled or not
* @param agentId the id of the agent to get enabled status
* @return true if the agent is enabled, false otherwise
*/
function isAgentEnabled(uint256 agentId) external view returns (bool);
/**
* @notice method to get the minimum delay for the agent
* minimum delay is the time in seconds since the lastUpdateTimestamp of an market and updateType
* which should pass before an update is allowed to be injected again
* @param agentId the id of the agent to get minimum delay
* @return minimum delay of the agent in seconds
*/
function getMinimumDelay(uint256 agentId) external view returns (uint256);
/**
* @notice method to get the agent context
* agent context could be used to store injection/validation configuration which used by the agent contract
* @param agentId the id of the agent for which to set the agent context
* @return the agent context of the agent in bytes
*/
function getAgentContext(uint256 agentId) external view returns (bytes memory);
/**
* @notice method to get if markets used for injection should be fetched from the agent contract or hub
* @param agentId the id of the agent for which to get the isMarketsFromAgentEnabled flag
* @return true if configured markets should be fetched from the agent, false if it should be fetched from the hub
* @dev if isMarketsFromAgentEnabled is false, the markets to fetch for injection is queried from the hub via allowedMarkets,
* if isMarketsFromAgentEnabled is true, the markets to fetch for injection is queried from the agent contract
* please note allowedMarkets is only used when isMarketsFromAgentEnabled is set to false, and restrictedMarkets
* is only applied when isMarketsFromAgentEnabled is true to filter out the markets from agent
*/
function isMarketsFromAgentEnabled(uint256 agentId) external view returns (bool);
/**
* @notice method to get the update type for the agent
* @param agentId the id of the agent for which to get the update type
* @return the update type configured for the agent
*/
function getUpdateType(uint256 agentId) external view returns (string memory);
/**
* @notice method to get the address of chaos risk oracle for the agent
* @param agentId the id of the agent to get the chaos risk oracle
* @return address of the chaos risk oracle configured for the agent
*/
function getRiskOracle(uint256 agentId) external view returns (address);
/**
* @notice method to get the total number of agents registered on the agent hub
* @return the total count of the agents registered
*/
function getAgentCount() external view returns (uint256);
/**
* @notice method to get last updated data for an agent and market pair
* @param agentId the id of the agent to get the last updated data
* @param market the address of the market to get the last updated data
* @return last updated data struct, including the latest updated timestamp and latest updated id
* which was injected for the agentId and market pair
*/
function getLastInjectedUpdate(
uint256 agentId,
address market
) external view returns (LastInjectedUpdate memory);
}
src/interfaces/IAgentHub.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IAgentConfigurator} from './IAgentConfigurator.sol';
/**
* @title IAgentHub
* @author BGD labs
* @notice Defines the interface for the AgentHub contract
*/
interface IAgentHub is IAgentConfigurator {
/**
* @notice There must be at least one action performed per execution
*/
error NoActionCanBePerformed();
/**
* @notice Struct storing data passed from check to execute to perform actions
*/
struct ActionData {
uint256 agentId;
address[] markets;
}
/**
* @notice run off-chain, checks if updates from the riskOracle could be injected or not
* @param agentIds contains the list of agentIds for which updates should be checked
* @return shouldExecute true if perform should be run, false otherwise
* @return actions contains the list of ActionData struct containing the agentId and markets
* for which updates could be injected
*/
function check(
uint256[] memory agentIds
) external view returns (bool shouldExecute, ActionData[] memory actions);
/**
* @notice method to inject updates for agents, should be run when check() returns true
* @param actions contains the list of ActionData for which updates can be injected
*/
function execute(ActionData[] memory actions) external;
}
src/interfaces/IBaseAgent.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IRiskOracle} from '../contracts/dependencies/IRiskOracle.sol';
/**
* @title IBaseAgent
* @author BGD labs
*/
interface IBaseAgent {
/**
* @notice The caller account is not the AgentHub contract
*/
error OnlyAgentHub(address account);
/**
* @notice method to get the address of the agent hub contract.
* @return agent hub contract address.
*/
function AGENT_HUB() external view returns (address);
/**
* @notice method to get all the market addresses to be used by the agent hub.
* this is a virtual method that must be implemented by the child contract
* to define custom dynamic market addresses to be used for a specific agent.
* @dev this method is used by the agent hub only when `isMarketsFromAgentEnabled` flag is set to true on hub.
* if flag is false, the markets from this agent contract will be ignored and markets from the hub will
* be used instead. please note, if the hub has configured restricted markets, those markets will be
* filtered out from the list of markets returned by this method.
* @param agentId the id of the agent
* @return the list of custom markets to be used by the agent hub for the agent
*/
function getMarkets(uint256 agentId) external view returns (address[] memory);
/**
* @notice method to perform agent-specific validation for a risk parameter update.
* this is a virtual method that must be implemented by the child contract
* to define custom validation logic for a specific agent
* @param agentId the id of the agent being validated
* @param agentContext contains custom config bytes data for the agent
* @param update risk parameter update to be validated
* @return indicates whether the proposed update is valid for the specified agent
* - true if the update meets the agent-specific validation criteria
* - false if the update does not pass validation
*/
function validate(
uint256 agentId,
bytes calldata agentContext,
IRiskOracle.RiskParameterUpdate calldata update
) external view returns (bool);
/**
* @notice method called by the agentHub to inject updates from risk oracle into the protocol
* @param agentId the id of the agent for which to do injection
* @param agentContext contains custom config bytes data for the agent
* @param update risk parameter update to be injected
*/
function inject(
uint256 agentId,
bytes calldata agentContext,
IRiskOracle.RiskParameterUpdate calldata update
) external;
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "shanghai",
"remappings": [
"solidity-utils/=lib/solidity-utils/src/",
"forge-std/=lib/solidity-utils/lib/forge-std/src/",
"openzeppelin-contracts-upgradeable/=lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
"aave-address-book/=lib/aave-address-book/src/",
"aave-v3-origin/=lib/aave-address-book/lib/aave-v3-origin/src/",
"@openzeppelin/contracts-upgradeable/=lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/contracts/",
"@openzeppelin/contracts/=lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
"ds-test/=lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/solidity-utils/lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.