Verified contractExactBUSL-1.1
ClearSwap
Address0x35e22bcc2c60c8a721cb36ce47ad562860a2d9cb
- Balance
0 ETH
- Transactions
10
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 24,592,039
- Creation transaction
- 0x676a447468…b9c63e790b
21 files
- project/contracts/swap/ClearSwap.solmain13.61 KB
- npm/@openzeppelin/[email protected]/proxy/utils/Initializable.sol9.28 KB
- npm/@openzeppelin/[email protected]/access/manager/AccessManaged.sol4.68 KB
- npm/@openzeppelin/[email protected]/access/manager/AuthorityUtils.sol1.38 KB
- npm/@openzeppelin/[email protected]/access/manager/IAccessManaged.sol1.11 KB
- npm/@openzeppelin/[email protected]/access/manager/IAccessManager.sol16.31 KB
- npm/@openzeppelin/[email protected]/access/manager/IAuthority.sol483 B
- npm/@openzeppelin/[email protected]/interfaces/IERC1363.sol4.45 KB
- npm/@openzeppelin/[email protected]/interfaces/IERC165.sol193 B
- npm/@openzeppelin/[email protected]/interfaces/IERC20.sol182 B
- npm/@openzeppelin/[email protected]/interfaces/IERC20Metadata.sol216 B
- npm/@openzeppelin/[email protected]/token/ERC20/IERC20.sol2.78 KB
- npm/@openzeppelin/[email protected]/token/ERC20/extensions/IERC20Metadata.sol684 B
- npm/@openzeppelin/[email protected]/token/ERC20/utils/SafeERC20.sol10.08 KB
- npm/@openzeppelin/[email protected]/utils/Context.sol963 B
- npm/@openzeppelin/[email protected]/utils/Pausable.sol2.71 KB
- npm/@openzeppelin/[email protected]/utils/introspection/IERC165.sol871 B
- project/contracts/interfaces/IClearOracle.sol5.1 KB
- project/contracts/interfaces/IClearSwap.sol5.34 KB
- project/contracts/interfaces/IClearVault.sol29.53 KB
- project/contracts/interfaces/external/ICurveStableSwapNG.sol1.82 KB
project/contracts/swap/ClearSwap.sol
// SPDX-License-Identifier: BUSL-1.1
//████████╗██████╗ ███████╗██╗ ██╗███████╗███████╗
//╚══██╔══╝██╔══██╗██╔════╝██║ ██║██╔════╝██╔════╝
// ██║ ██████╔╝█████╗ ██║ ██║█████╗ █████╗
// ██║ ██╔══██╗██╔══╝ ╚██╗ ██╔╝██╔══╝ ██╔══╝
// ██║ ██║ ██║███████╗ ╚████╔╝ ███████╗███████╗
// ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═══╝ ╚══════╝╚══════╝
pragma solidity ^0.8.24;
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {AccessManaged} from "@openzeppelin/contracts/access/manager/AccessManaged.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IClearSwap} from "../interfaces/IClearSwap.sol";
import {IClearOracle} from "../interfaces/IClearOracle.sol";
import {IClearVault} from "../interfaces/IClearVault.sol";
import {ICurveStableSwapNG} from "../interfaces/external/ICurveStableSwapNG.sol";
/**
* @title ClearSwap
* @notice Automated market maker for swapping between vault tokens with IOU token support
* @dev Enables swaps between tokens using vault liquidity with automatic IOU minting when liquidity is insufficient.
* Integrates with Curve pools for IOU/token trading and includes depeg protection mechanisms.
* @author Clear Protocol Team
*/
contract ClearSwap is AccessManaged, Pausable, IClearSwap {
/// @notice The price oracle used to fetch USD prices and swap rates
IClearOracle public oracle;
/// @notice Minimum depeg threshold: swaps are only allowed when the input asset price
/// is below this fraction of the output asset price (basis points, 10000 = 100%)
uint256 public depegThresholdBps;
/// @notice Maximum depeg threshold: swaps are blocked when the input asset price has
/// depegged too severely below the output price (basis points, 10000 = 100%)
uint256 public maximalDepegThresholdBps;
/**
* @notice Deploys the ClearSwap contract with oracle and depeg protection configuration
* @param _initialAuthority The address of the access control authority contract
* @param _oracle The ClearOracle contract address used for price lookups
* @param _depegThresholdBps Minimum depeg threshold in basis points (must be > _maximalDepegThresholdBps)
* @param _maximalDepegThresholdBps Maximum depeg threshold in basis points (must be < _depegThresholdBps)
*/
constructor(
address _initialAuthority,
address _oracle,
uint256 _depegThresholdBps,
uint256 _maximalDepegThresholdBps
) AccessManaged(_initialAuthority) Pausable() {
if(_depegThresholdBps > 10000) revert InvalidInput();
if(_maximalDepegThresholdBps > 10000) revert InvalidInput();
if(_maximalDepegThresholdBps >= _depegThresholdBps) revert InvalidInput();
oracle = IClearOracle(_oracle);
depegThresholdBps = _depegThresholdBps;
maximalDepegThresholdBps = _maximalDepegThresholdBps;
emit DepegTresholdUpdated(_depegThresholdBps, _maximalDepegThresholdBps);
}
/**
* @notice Updates the depeg threshold for swap protection
* @dev Changes the minimum price ratio required for swaps to prevent exploitation of depegged assets
* @param _depegThresholdBps New depeg threshold in basis points (10000 = 100%)
* @custom:emits DepegTresholdUpdated
*/
function setDepegTresholdBps(
uint256 _depegThresholdBps,
uint256 _maximalDepegThresholdBps
) external restricted {
if(_depegThresholdBps > 10000) revert InvalidInput();
if(_maximalDepegThresholdBps > 10000) revert InvalidInput();
if(_maximalDepegThresholdBps >= _depegThresholdBps) revert InvalidInput();
depegThresholdBps = _depegThresholdBps;
maximalDepegThresholdBps = _maximalDepegThresholdBps;
emit DepegTresholdUpdated(_depegThresholdBps, _maximalDepegThresholdBps);
}
/**
* @notice Returns the current depeg threshold configuration for swap protection
* @dev Retrieves both minimum and maximum depeg thresholds used in swap validation
* @return _depegThresholdBps The minimum depeg threshold in basis points (10000 = 100%)
* @return _maximalDepegThresholdBps The maximum depeg threshold in basis points (10000 = 100%)
*/
function getDepegTresholdBps() external view returns (
uint256 _depegThresholdBps,
uint256 _maximalDepegThresholdBps
) {
_depegThresholdBps = depegThresholdBps;
_maximalDepegThresholdBps = maximalDepegThresholdBps;
}
/**
* @notice Internal function to calculate swap output amounts including IOU tokens
* @dev Calculates direct swap amount and IOU tokens needed based on price differences
* Validates depeg protection conditions before allowing swaps
* @param _from The input token address
* @param _to The output token address
* @param _amountIn The amount of input tokens
* @return amountOut Amount of output tokens from direct swap
* @return ious Amount of IOU tokens to be minted (if any)
* @custom:throws AssetIsNotDepeg if input asset is not sufficiently depegged
* @custom:throws OutAssetIsDepeg if output asset is depegged
*/
function _calculateSwapOutput(
address _from,
address _to,
uint256 _amountIn
) internal view returns (uint256 amountOut, uint256 ious) {
if(_amountIn == 0) return (0,0);
(
uint256 _fromPrice,
uint256 _toPrice,
uint256 _fromRedemptionPrice,
uint256 _toRedemptionPrice,
uint8 _fromPriceDecimals,
uint8 _toPriceDecimals,
uint256 _amountOut
) = oracle.getSwapData(_from, _to, _amountIn);
uint256 _depegThresholdBps = depegThresholdBps;
if(_fromPrice > _toPrice * _depegThresholdBps / 10000) revert AssetIsNotDepeg();
if(_fromPrice >= _fromRedemptionPrice) revert AssetIsOverRedemptionPrice();
if(_fromPrice < _toPrice * maximalDepegThresholdBps / 10000) revert AssetDepegIsTooHigh();
if(_toPrice < _toRedemptionPrice * _depegThresholdBps / 10000) revert OutAssetIsDepeg();
amountOut = _amountOut;
uint256 _iouRedemptionPrice = _fromRedemptionPrice < _toRedemptionPrice
? _fromRedemptionPrice
: _toRedemptionPrice;
if(_fromPrice < _iouRedemptionPrice) {
uint256 iousBase = _amountIn * (_iouRedemptionPrice - _fromPrice) / 10 ** _fromPriceDecimals;
ious = (iousBase * 10 ** _toPriceDecimals) / _toPrice;
}
}
/**
* @notice Previews the expected output amounts of a swap without executing it
* @dev Calculates direct token output and potential IOU tokens after applying vault fees.
* When _receiveIOU is false, IOU tokens are further swapped via the Curve meta pool
* and the combined token output is returned.
* @param _vault The vault address that would execute the swap
* @param _from The input token address
* @param _to The output token address
* @param _amountIn The amount of input tokens to preview
* @param _receiveIOU If true, return IOU amount separately; if false, estimate Curve swap for IOUs
* @return amountOut Expected amount of output tokens (includes Curve IOU swap if !_receiveIOU)
* @return ious Expected amount of IOU tokens minted after fees (0 if !_receiveIOU)
*/
function previewSwap(
address _vault,
address _from,
address _to,
uint256 _amountIn,
bool _receiveIOU
) public view returns (uint256 amountOut, uint256 ious) {
(amountOut, ious) = _calculateSwapOutput(
_from,
_to,
_amountIn
);
(uint256 lpFeeBps, uint256 treasuryFee) = IClearVault(_vault).iouFeeBps();
ious = ious - (ious * (lpFeeBps + treasuryFee) / 10000);
if(!_receiveIOU) {
address metapool = IClearVault(_vault).iouCurveMetaPoolOf(_from);
uint256 tokenOutCurvePoolIndex = IClearVault(_vault).tokensCurvePoolIndexOf(_to);
uint256 iouSwapOutput = ICurveStableSwapNG(metapool).get_dy_underlying(
int128(0),
int128(1) + int128(uint128(tokenOutCurvePoolIndex)),
ious
);
return (amountOut + iouSwapOutput, 0);
} else {
return (amountOut, ious);
}
}
/**
* @notice Executes a token swap through the specified vault
* @dev Transfers input tokens, executes vault swap, and handles IOU redemption via Curve if requested
* Can either return IOU tokens directly or swap them for underlying tokens via Curve pool
* @param _receiver The address to receive the output tokens
* @param _vault The vault address to execute the swap through
* @param _from The input token address
* @param _to The output token address
* @param _amountIn The amount of input tokens to swap
* @param _minAmountOut Minimum amount of output tokens expected (slippage protection)
* @param _receiveIOU Whether to receive IOU tokens directly or swap them for underlying
* @return amountOut Actual amount of output tokens received
* @return ious Amount of IOU tokens received (0 if swapped via Curve)
* @custom:throws InsufficientAmountOut if output is below minimum
*/
function swap(
address _receiver,
address _vault,
address _from,
address _to,
uint256 _amountIn,
uint256 _minAmountOut,
bool _receiveIOU
) public whenNotPaused returns (uint256 amountOut, uint256 ious) {
if(_amountIn == 0) revert InvalidInput();
if(_receiver == address(0)) revert InvalidReceiver();
(amountOut, ious) = _calculateSwapOutput(
_from,
_to,
_amountIn
);
SafeERC20.safeTransferFrom(IERC20(_from), msg.sender, _vault, _amountIn);
uint256 iousReceived = IClearVault(_vault).swapLiquidity(
_receiveIOU ? _receiver : address(this),
_from,
_to,
_amountIn,
amountOut,
ious
);
if(!_receiveIOU && ious > 0) {
address iou = IClearVault(_vault).iouOf(_from);
address metapool = IClearVault(_vault).iouCurveMetaPoolOf(_from);
uint256 tokenOutCurvePoolIndex = IClearVault(_vault).tokensCurvePoolIndexOf(_to);
SafeERC20.safeIncreaseAllowance(IERC20(iou), metapool, iousReceived);
uint256 iouSwapOutput = ICurveStableSwapNG(metapool).exchange_underlying(
int128(0),
int128(1) + int128(uint128(tokenOutCurvePoolIndex)),
iousReceived,
0
);
if(_minAmountOut > amountOut + iouSwapOutput) revert InsufficientAmountOut();
SafeERC20.safeTransfer(IERC20(_to), _receiver, amountOut + iouSwapOutput);
return (amountOut + iouSwapOutput, 0);
} else {
if(_minAmountOut > amountOut) revert InsufficientAmountOut();
return (amountOut, ious);
}
}
/**
* @notice Redeems IOU tokens for underlying tokens when price conditions allow
* @dev Validates that token price has recovered above redemption price before allowing redemption
* Burns IOU tokens from sender and transfers underlying tokens to receiver
* @param _receiver The address to receive the underlying tokens
* @param _vault The vault address that manages the IOU tokens
* @param _token The underlying token address
* @param _amount The amount of IOU tokens to redeem
* @custom:throws RedemptionNotOpened if token price is still below redemption price
*/
function redeemIOU(
address _receiver,
address _vault,
address _token,
uint256 _amount
) public whenNotPaused {
if(_receiver == address(0)) revert InvalidReceiver();
if(!IClearVault(_vault).isBalanced()) revert RedemptionNotOpened();
IClearVault(_vault).redeemIOU(
msg.sender,
_receiver,
_token,
_amount
);
}
/**
* @notice Pauses all swap and IOU redemption operations
* @dev Triggers the stopped state; all functions guarded by whenNotPaused will revert.
* Only callable by authorized addresses. The contract must not already be paused.
*/
function pause() external restricted {
_pause();
}
/**
* @notice Unpauses swap and IOU redemption operations, restoring normal functionality
* @dev Returns to the active state; whenNotPaused functions become available again.
* Only callable by authorized addresses. The contract must currently be paused.
*/
function unpause() external restricted {
_unpause();
}
}
npm/@openzeppelin/[email protected]/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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 reinitialization) 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 Pointer to storage slot. Allows integrators to override it with a custom storage location.
*
* NOTE: Consider following the ERC-7201 formula to derive storage locations.
*/
function _initializableStorageSlot() internal pure virtual returns (bytes32) {
return INITIALIZABLE_STORAGE;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
bytes32 slot = _initializableStorageSlot();
assembly {
$.slot := slot
}
}
}
npm/@openzeppelin/[email protected]/access/manager/AccessManaged.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/manager/AccessManaged.sol)
pragma solidity ^0.8.20;
import {AuthorityUtils} from "./AuthorityUtils.sol";
import {IAccessManager} from "./IAccessManager.sol";
import {IAccessManaged} from "./IAccessManaged.sol";
import {Context} from "../../utils/Context.sol";
/**
* @dev This contract module makes available a {restricted} modifier. Functions decorated with this modifier will be
* permissioned according to an "authority": a contract like {AccessManager} that follows the {IAuthority} interface,
* implementing a policy that allows certain callers to access certain functions.
*
* IMPORTANT: The `restricted` modifier should never be used on `internal` functions, judiciously used in `public`
* functions, and ideally only used in `external` functions. See {restricted}.
*/
abstract contract AccessManaged is Context, IAccessManaged {
address private _authority;
bool private _consumingSchedule;
/**
* @dev Initializes the contract connected to an initial authority.
*/
constructor(address initialAuthority) {
_setAuthority(initialAuthority);
}
/**
* @dev Restricts access to a function as defined by the connected Authority for this contract and the
* caller and selector of the function that entered the contract.
*
* [IMPORTANT]
* ====
* In general, this modifier should only be used on `external` functions. It is okay to use it on `public`
* functions that are used as external entry points and are not called internally. Unless you know what you're
* doing, it should never be used on `internal` functions. Failure to follow these rules can have critical security
* implications! This is because the permissions are determined by the function that entered the contract, i.e. the
* function at the bottom of the call stack, and not the function where the modifier is visible in the source code.
* ====
*
* [WARNING]
* ====
* Avoid adding this modifier to the https://docs.soliditylang.org/en/v0.8.20/contracts.html#receive-ether-function[`receive()`]
* function or the https://docs.soliditylang.org/en/v0.8.20/contracts.html#fallback-function[`fallback()`]. These
* functions are the only execution paths where a function selector cannot be unambiguously determined from the calldata
* since the selector defaults to `0x00000000` in the `receive()` function and similarly in the `fallback()` function
* if no calldata is provided. (See {_checkCanCall}).
*
* The `receive()` function will always panic whereas the `fallback()` may panic depending on the calldata length.
* ====
*/
modifier restricted() {
_checkCanCall(_msgSender(), _msgData());
_;
}
/// @inheritdoc IAccessManaged
function authority() public view virtual returns (address) {
return _authority;
}
/// @inheritdoc IAccessManaged
function setAuthority(address newAuthority) public virtual {
address caller = _msgSender();
if (caller != authority()) {
revert AccessManagedUnauthorized(caller);
}
if (newAuthority.code.length == 0) {
revert AccessManagedInvalidAuthority(newAuthority);
}
_setAuthority(newAuthority);
}
/// @inheritdoc IAccessManaged
function isConsumingScheduledOp() public view returns (bytes4) {
return _consumingSchedule ? this.isConsumingScheduledOp.selector : bytes4(0);
}
/**
* @dev Transfers control to a new authority. Internal function with no access restriction. Allows bypassing the
* permissions set by the current authority.
*/
function _setAuthority(address newAuthority) internal virtual {
_authority = newAuthority;
emit AuthorityUpdated(newAuthority);
}
/**
* @dev Reverts if the caller is not allowed to call the function identified by a selector. Panics if the calldata
* is less than 4 bytes long.
*/
function _checkCanCall(address caller, bytes calldata data) internal virtual {
(bool immediate, uint32 delay) = AuthorityUtils.canCallWithDelay(
authority(),
caller,
address(this),
bytes4(data[0:4])
);
if (!immediate) {
if (delay > 0) {
_consumingSchedule = true;
IAccessManager(authority()).consumeScheduledOp(caller, data);
_consumingSchedule = false;
} else {
revert AccessManagedUnauthorized(caller);
}
}
}
}
npm/@openzeppelin/[email protected]/access/manager/AuthorityUtils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (access/manager/AuthorityUtils.sol)
pragma solidity ^0.8.20;
import {IAuthority} from "./IAuthority.sol";
library AuthorityUtils {
/**
* @dev Since `AccessManager` implements an extended IAuthority interface, invoking `canCall` with backwards compatibility
* for the preexisting `IAuthority` interface requires special care to avoid reverting on insufficient return data.
* This helper function takes care of invoking `canCall` in a backwards compatible way without reverting.
*/
function canCallWithDelay(
address authority,
address caller,
address target,
bytes4 selector
) internal view returns (bool immediate, uint32 delay) {
bytes memory data = abi.encodeCall(IAuthority.canCall, (caller, target, selector));
assembly ("memory-safe") {
mstore(0x00, 0x00)
mstore(0x20, 0x00)
if staticcall(gas(), authority, add(data, 0x20), mload(data), 0x00, 0x40) {
immediate := mload(0x00)
delay := mload(0x20)
// If delay does not fit in a uint32, return 0 (no delay)
// equivalent to: if gt(delay, 0xFFFFFFFF) { delay := 0 }
delay := mul(delay, iszero(shr(32, delay)))
}
}
}
}
npm/@openzeppelin/[email protected]/access/manager/IAccessManaged.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/manager/IAccessManaged.sol)
pragma solidity >=0.8.4;
interface IAccessManaged {
/**
* @dev Authority that manages this contract was updated.
*/
event AuthorityUpdated(address authority);
error AccessManagedUnauthorized(address caller);
error AccessManagedRequiredDelay(address caller, uint32 delay);
error AccessManagedInvalidAuthority(address authority);
/**
* @dev Returns the current authority.
*/
function authority() external view returns (address);
/**
* @dev Transfers control to a new authority. The caller must be the current authority.
*/
function setAuthority(address) external;
/**
* @dev Returns true only in the context of a delayed restricted call, at the moment that the scheduled operation is
* being consumed. Prevents denial of service for delayed restricted calls in the case that the contract performs
* attacker controlled calls.
*/
function isConsumingScheduledOp() external view returns (bytes4);
}
npm/@openzeppelin/[email protected]/access/manager/IAccessManager.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/manager/IAccessManager.sol)
pragma solidity >=0.8.4;
interface IAccessManager {
/**
* @dev A delayed operation was scheduled.
*/
event OperationScheduled(
bytes32 indexed operationId,
uint32 indexed nonce,
uint48 schedule,
address caller,
address target,
bytes data
);
/**
* @dev A scheduled operation was executed.
*/
event OperationExecuted(bytes32 indexed operationId, uint32 indexed nonce);
/**
* @dev A scheduled operation was canceled.
*/
event OperationCanceled(bytes32 indexed operationId, uint32 indexed nonce);
/**
* @dev Informational labelling for a roleId.
*/
event RoleLabel(uint64 indexed roleId, string label);
/**
* @dev Emitted when `account` is granted `roleId`.
*
* NOTE: The meaning of the `since` argument depends on the `newMember` argument.
* If the role is granted to a new member, the `since` argument indicates when the account becomes a member of the role,
* otherwise it indicates the execution delay for this account and roleId is updated.
*/
event RoleGranted(uint64 indexed roleId, address indexed account, uint32 delay, uint48 since, bool newMember);
/**
* @dev Emitted when `account` membership or `roleId` is revoked. Unlike granting, revoking is instantaneous.
*/
event RoleRevoked(uint64 indexed roleId, address indexed account);
/**
* @dev Role acting as admin over a given `roleId` is updated.
*/
event RoleAdminChanged(uint64 indexed roleId, uint64 indexed admin);
/**
* @dev Role acting as guardian over a given `roleId` is updated.
*/
event RoleGuardianChanged(uint64 indexed roleId, uint64 indexed guardian);
/**
* @dev Grant delay for a given `roleId` will be updated to `delay` when `since` is reached.
*/
event RoleGrantDelayChanged(uint64 indexed roleId, uint32 delay, uint48 since);
/**
* @dev Target mode is updated (true = closed, false = open).
*/
event TargetClosed(address indexed target, bool closed);
/**
* @dev Role required to invoke `selector` on `target` is updated to `roleId`.
*/
event TargetFunctionRoleUpdated(address indexed target, bytes4 selector, uint64 indexed roleId);
/**
* @dev Admin delay for a given `target` will be updated to `delay` when `since` is reached.
*/
event TargetAdminDelayUpdated(address indexed target, uint32 delay, uint48 since);
error AccessManagerAlreadyScheduled(bytes32 operationId);
error AccessManagerNotScheduled(bytes32 operationId);
error AccessManagerNotReady(bytes32 operationId);
error AccessManagerExpired(bytes32 operationId);
error AccessManagerLockedRole(uint64 roleId);
error AccessManagerBadConfirmation();
error AccessManagerUnauthorizedAccount(address msgsender, uint64 roleId);
error AccessManagerUnauthorizedCall(address caller, address target, bytes4 selector);
error AccessManagerUnauthorizedConsume(address target);
error AccessManagerUnauthorizedCancel(address msgsender, address caller, address target, bytes4 selector);
error AccessManagerInvalidInitialAdmin(address initialAdmin);
/**
* @dev Check if an address (`caller`) is authorised to call a given function on a given contract directly (with
* no restriction). Additionally, it returns the delay needed to perform the call indirectly through the {schedule}
* & {execute} workflow.
*
* This function is usually called by the targeted contract to control immediate execution of restricted functions.
* Therefore we only return true if the call can be performed without any delay. If the call is subject to a
* previously set delay (not zero), then the function should return false and the caller should schedule the operation
* for future execution.
*
* If `allowed` is true, the delay can be disregarded and the operation can be immediately executed, otherwise
* the operation can be executed if and only if delay is greater than 0.
*
* NOTE: The IAuthority interface does not include the `uint32` delay. This is an extension of that interface that
* is backward compatible. Some contracts may thus ignore the second return argument. In that case they will fail
* to identify the indirect workflow, and will consider calls that require a delay to be forbidden.
*
* NOTE: This function does not report the permissions of the admin functions in the manager itself. These are defined by the
* {AccessManager} documentation.
*/
function canCall(
address caller,
address target,
bytes4 selector
) external view returns (bool allowed, uint32 delay);
/**
* @dev Expiration delay for scheduled proposals. Defaults to 1 week.
*
* IMPORTANT: Avoid overriding the expiration with 0. Otherwise every contract proposal will be expired immediately,
* disabling any scheduling usage.
*/
function expiration() external view returns (uint32);
/**
* @dev Minimum setback for all delay updates, with the exception of execution delays. It
* can be increased without setback (and reset via {revokeRole} in the case event of an
* accidental increase). Defaults to 5 days.
*/
function minSetback() external view returns (uint32);
/**
* @dev Get whether the contract is closed disabling any access. Otherwise role permissions are applied.
*
* NOTE: When the manager itself is closed, admin functions are still accessible to avoid locking the contract.
*/
function isTargetClosed(address target) external view returns (bool);
/**
* @dev Get the role required to call a function.
*/
function getTargetFunctionRole(address target, bytes4 selector) external view returns (uint64);
/**
* @dev Get the admin delay for a target contract. Changes to contract configuration are subject to this delay.
*/
function getTargetAdminDelay(address target) external view returns (uint32);
/**
* @dev Get the id of the role that acts as an admin for the given role.
*
* The admin permission is required to grant the role, revoke the role and update the execution delay to execute
* an operation that is restricted to this role.
*/
function getRoleAdmin(uint64 roleId) external view returns (uint64);
/**
* @dev Get the role that acts as a guardian for a given role.
*
* The guardian permission allows canceling operations that have been scheduled under the role.
*/
function getRoleGuardian(uint64 roleId) external view returns (uint64);
/**
* @dev Get the role current grant delay.
*
* Its value may change at any point without an event emitted following a call to {setGrantDelay}.
* Changes to this value, including effect timepoint are notified in advance by the {RoleGrantDelayChanged} event.
*/
function getRoleGrantDelay(uint64 roleId) external view returns (uint32);
/**
* @dev Get the access details for a given account for a given role. These details include the timepoint at which
* membership becomes active, and the delay applied to all operation by this user that requires this permission
* level.
*
* Returns:
* [0] Timestamp at which the account membership becomes valid. 0 means role is not granted.
* [1] Current execution delay for the account.
* [2] Pending execution delay for the account.
* [3] Timestamp at which the pending execution delay will become active. 0 means no delay update is scheduled.
*/
function getAccess(
uint64 roleId,
address account
) external view returns (uint48 since, uint32 currentDelay, uint32 pendingDelay, uint48 effect);
/**
* @dev Check if a given account currently has the permission level corresponding to a given role. Note that this
* permission might be associated with an execution delay. {getAccess} can provide more details.
*/
function hasRole(uint64 roleId, address account) external view returns (bool isMember, uint32 executionDelay);
/**
* @dev Give a label to a role, for improved role discoverability by UIs.
*
* Requirements:
*
* - the caller must be a global admin
*
* Emits a {RoleLabel} event.
*/
function labelRole(uint64 roleId, string calldata label) external;
/**
* @dev Add `account` to `roleId`, or change its execution delay.
*
* This gives the account the authorization to call any function that is restricted to this role. An optional
* execution delay (in seconds) can be set. If that delay is non 0, the user is required to schedule any operation
* that is restricted to members of this role. The user will only be able to execute the operation after the delay has
* passed, before it has expired. During this period, admin and guardians can cancel the operation (see {cancel}).
*
* If the account has already been granted this role, the execution delay will be updated. This update is not
* immediate and follows the delay rules. For example, if a user currently has a delay of 3 hours, and this is
* called to reduce that delay to 1 hour, the new delay will take some time to take effect, enforcing that any
* operation executed in the 3 hours that follows this update was indeed scheduled before this update.
*
* Requirements:
*
* - the caller must be an admin for the role (see {getRoleAdmin})
* - granted role must not be the `PUBLIC_ROLE`
*
* Emits a {RoleGranted} event.
*/
function grantRole(uint64 roleId, address account, uint32 executionDelay) external;
/**
* @dev Remove an account from a role, with immediate effect. If the account does not have the role, this call has
* no effect.
*
* Requirements:
*
* - the caller must be an admin for the role (see {getRoleAdmin})
* - revoked role must not be the `PUBLIC_ROLE`
*
* Emits a {RoleRevoked} event if the account had the role.
*/
function revokeRole(uint64 roleId, address account) external;
/**
* @dev Renounce role permissions for the calling account with immediate effect. If the sender is not in
* the role this call has no effect.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* Emits a {RoleRevoked} event if the account had the role.
*/
function renounceRole(uint64 roleId, address callerConfirmation) external;
/**
* @dev Change admin role for a given role.
*
* Requirements:
*
* - the caller must be a global admin
*
* Emits a {RoleAdminChanged} event
*/
function setRoleAdmin(uint64 roleId, uint64 admin) external;
/**
* @dev Change guardian role for a given role.
*
* Requirements:
*
* - the caller must be a global admin
*
* Emits a {RoleGuardianChanged} event
*/
function setRoleGuardian(uint64 roleId, uint64 guardian) external;
/**
* @dev Update the delay for granting a `roleId`.
*
* Requirements:
*
* - the caller must be a global admin
*
* Emits a {RoleGrantDelayChanged} event.
*/
function setGrantDelay(uint64 roleId, uint32 newDelay) external;
/**
* @dev Set the role required to call functions identified by the `selectors` in the `target` contract.
*
* Requirements:
*
* - the caller must be a global admin
*
* Emits a {TargetFunctionRoleUpdated} event per selector.
*/
function setTargetFunctionRole(address target, bytes4[] calldata selectors, uint64 roleId) external;
/**
* @dev Set the delay for changing the configuration of a given target contract.
*
* Requirements:
*
* - the caller must be a global admin
*
* Emits a {TargetAdminDelayUpdated} event.
*/
function setTargetAdminDelay(address target, uint32 newDelay) external;
/**
* @dev Set the closed flag for a contract.
*
* Closing the manager itself won't disable access to admin methods to avoid locking the contract.
*
* Requirements:
*
* - the caller must be a global admin
*
* Emits a {TargetClosed} event.
*/
function setTargetClosed(address target, bool closed) external;
/**
* @dev Return the timepoint at which a scheduled operation will be ready for execution. This returns 0 if the
* operation is not yet scheduled, has expired, was executed, or was canceled.
*/
function getSchedule(bytes32 id) external view returns (uint48);
/**
* @dev Return the nonce for the latest scheduled operation with a given id. Returns 0 if the operation has never
* been scheduled.
*/
function getNonce(bytes32 id) external view returns (uint32);
/**
* @dev Schedule a delayed operation for future execution, and return the operation identifier. It is possible to
* choose the timestamp at which the operation becomes executable as long as it satisfies the execution delays
* required for the caller. The special value zero will automatically set the earliest possible time.
*
* Returns the `operationId` that was scheduled. Since this value is a hash of the parameters, it can reoccur when
* the same parameters are used; if this is relevant, the returned `nonce` can be used to uniquely identify this
* scheduled operation from other occurrences of the same `operationId` in invocations of {execute} and {cancel}.
*
* Emits a {OperationScheduled} event.
*
* NOTE: It is not possible to concurrently schedule more than one operation with the same `target` and `data`. If
* this is necessary, a random byte can be appended to `data` to act as a salt that will be ignored by the target
* contract if it is using standard Solidity ABI encoding.
*/
function schedule(
address target,
bytes calldata data,
uint48 when
) external returns (bytes32 operationId, uint32 nonce);
/**
* @dev Execute a function that is delay restricted, provided it was properly scheduled beforehand, or the
* execution delay is 0.
*
* Returns the nonce that identifies the previously scheduled operation that is executed, or 0 if the
* operation wasn't previously scheduled (if the caller doesn't have an execution delay).
*
* Emits an {OperationExecuted} event only if the call was scheduled and delayed.
*/
function execute(address target, bytes calldata data) external payable returns (uint32);
/**
* @dev Cancel a scheduled (delayed) operation. Returns the nonce that identifies the previously scheduled
* operation that is cancelled.
*
* Requirements:
*
* - the caller must be the proposer, a guardian of the targeted function, or a global admin
*
* Emits a {OperationCanceled} event.
*/
function cancel(address caller, address target, bytes calldata data) external returns (uint32);
/**
* @dev Consume a scheduled operation targeting the caller. If such an operation exists, mark it as consumed
* (emit an {OperationExecuted} event and clean the state). Otherwise, throw an error.
*
* This is useful for contract that want to enforce that calls targeting them were scheduled on the manager,
* with all the verifications that it implies.
*
* Emit a {OperationExecuted} event.
*/
function consumeScheduledOp(address caller, bytes calldata data) external;
/**
* @dev Hashing function for delayed operations.
*/
function hashOperation(address caller, address target, bytes calldata data) external view returns (bytes32);
/**
* @dev Changes the authority of a target managed by this manager instance.
*
* Requirements:
*
* - the caller must be a global admin
*/
function updateAuthority(address target, address newAuthority) external;
}
npm/@openzeppelin/[email protected]/access/manager/IAuthority.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/manager/IAuthority.sol)
pragma solidity >=0.4.16;
/**
* @dev Standard interface for permissioning originally defined in Dappsys.
*/
interface IAuthority {
/**
* @dev Returns true if the caller can invoke on a target the function identified by a function selector.
*/
function canCall(address caller, address target, bytes4 selector) external view returns (bool allowed);
}
npm/@openzeppelin/[email protected]/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
npm/@openzeppelin/[email protected]/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
npm/@openzeppelin/[email protected]/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
npm/@openzeppelin/[email protected]/interfaces/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
npm/@openzeppelin/[email protected]/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
npm/@openzeppelin/[email protected]/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
npm/@openzeppelin/[email protected]/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
npm/@openzeppelin/[email protected]/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
npm/@openzeppelin/[email protected]/utils/Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
npm/@openzeppelin/[email protected]/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
project/contracts/interfaces/IClearOracle.sol
// SPDX-License-Identifier: MIT
//████████╗██████╗ ███████╗██╗ ██╗███████╗███████╗
//╚══██╔══╝██╔══██╗██╔════╝██║ ██║██╔════╝██╔════╝
// ██║ ██████╔╝█████╗ ██║ ██║█████╗ █████╗
// ██║ ██╔══██╗██╔══╝ ╚██╗ ██╔╝██╔══╝ ██╔══╝
// ██║ ██║ ██║███████╗ ╚████╔╝ ███████╗███████╗
// ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═══╝ ╚══════╝╚══════╝
pragma solidity ^0.8.24;
/**
* @title IClearOracle
* @notice Interface for the Clear protocol's price oracle system
* @dev Defines functions and events for managing asset price feeds with multiple adapter support
* @author Clear Protocol Team
*/
interface IClearOracle {
error OracleNotEnabled(address asset);
error OraclePriceOutdated(address asset, uint256 lastUpdate);
error InvalidTTL();
error SequencerDown();
error SequencerGracePeriodNotOver();
error BadInputsLength();
event ClearOracleSequencerCheckEnabled(address sequencer);
event ClearOracleRateChanged(address indexed asset, uint256 price);
enum ClearOracleAdaptersType {
CUSTOM,
CHAINLINK
}
event OracleConfigured(
bool indexed enabled,
address indexed asset,
uint8 assetDecimals,
uint8 oracleDecimals,
uint256 priceTTL,
uint256 redemptionPrice,
ClearOracleAdaptersType adapterType,
address adapter
);
struct OracleConfig {
bool enabled;
uint8 assetDecimals;
uint8 oracleDecimals;
uint256 price;
uint256 redemptionPrice;
uint256 priceTTL;
uint256 lastUpdateTimestamp;
ClearOracleAdaptersType adapterType;
address adapter;
}
struct OracleStorage {
mapping(address => OracleConfig) entries;
bool enableL2SequencerCheck;
address sequencerUptimeFeed;
}
/**
* @notice Returns the current USD price for a given asset
* @dev Retrieves the latest price from the configured oracle adapter
* Validates price freshness and sequencer status if enabled
* @param _asset The address of the asset to get the price for
* @return price The current price in USD scaled by oracle decimals
*/
function getUSDPrice(
address _asset
) external view returns (uint256 price);
/**
* @notice Returns both current price and redemption price for an asset
* @dev Gets the current market price and the fixed redemption price used for IOU operations
* @param _asset The address of the asset to query
* @return price The current market price in USD scaled by oracle decimals
* @return redemptionPrice The fixed redemption price for IOU calculations
*/
function getPriceAndRedemptionPrice(
address _asset
) external view returns (uint256 price, uint256 redemptionPrice);
/**
* @notice Calculates the exchange rate between two assets
* @dev Computes how much of the target asset would be received for the input amount
* Uses current USD prices and adjusts for decimal differences
* @param _from The input asset address
* @param _to The output asset address
* @param _amount The amount of input asset
* @return The equivalent amount of output asset
*/
function getRate(
address _from,
address _to,
uint256 _amount
) external view returns (uint256);
/**
* @notice Returns comprehensive swap data for two assets
* @dev Provides all price information needed for swap calculations including decimals
* Used by swap contracts to determine exchange rates and IOU minting amounts
* @param _from The input asset address
* @param _to The output asset address
* @param _amount The amount of input asset
* @return fromPrice Current USD price of input asset
* @return toPrice Current USD price of output asset
* @return fromRedemptionPrice Fixed redemption price of input asset for IOU calculations
* @return toRedemptionPrice Fixed redemption price of output asset for IOU calculations
* @return fromPriceDecimals Decimal places for input asset price
* @return toPriceDecimals Decimal places for output asset price
* @return amountOut Calculated amount of output asset
*/
function getSwapData(
address _from,
address _to,
uint256 _amount
) external view returns (
uint256 fromPrice,
uint256 toPrice,
uint256 fromRedemptionPrice,
uint256 toRedemptionPrice,
uint8 fromPriceDecimals,
uint8 toPriceDecimals,
uint256 amountOut
);
}
project/contracts/interfaces/IClearSwap.sol
// SPDX-License-Identifier: MIT
//████████╗██████╗ ███████╗██╗ ██╗███████╗███████╗
//╚══██╔══╝██╔══██╗██╔════╝██║ ██║██╔════╝██╔════╝
// ██║ ██████╔╝█████╗ ██║ ██║█████╗ █████╗
// ██║ ██╔══██╗██╔══╝ ╚██╗ ██╔╝██╔══╝ ██╔══╝
// ██║ ██║ ██║███████╗ ╚████╔╝ ███████╗███████╗
// ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═══╝ ╚══════╝╚══════╝
pragma solidity ^0.8.24;
import "./IClearOracle.sol";
/**
* @title IClearSwap
* @notice Interface for Clear protocol's swap contract with IOU support
* @dev Defines functions for token swapping with automatic IOU minting and redemption
* @author Clear Protocol Team
*/
interface IClearSwap {
error InvalidReceiver();
error InvalidInput();
error AssetIsNotDepeg();
error AssetIsOverRedemptionPrice();
error OutAssetIsDepeg();
error AssetDepegIsTooHigh();
error RedemptionNotOpened();
error InsufficientAmountOut();
event DepegTresholdUpdated(uint256 depegThresholdBps, uint256 maximalDepegThresholdBps);
/**
* @notice Returns the current depeg threshold configuration
* @dev Gets both the minimum and maximum depeg thresholds used for swap validation
* @return depegThresholdBps The minimum depeg threshold in basis points below which swaps are blocked
* @return maximalDepegThresholdBps The maximum depeg threshold in basis points above which swaps are blocked
*/
function getDepegTresholdBps() external view returns (
uint256 depegThresholdBps,
uint256 maximalDepegThresholdBps
);
/**
* @notice Updates the depeg threshold configuration for swap protection
* @dev Sets the price ratio boundaries that determine when swaps are allowed or blocked
* Only callable by authorized administrators
* @param _depegThresholdBps New minimum depeg threshold in basis points (10000 = 100%)
* @param _maximalDepegThresholdBps New maximum depeg threshold in basis points (10000 = 100%)
*/
function setDepegTresholdBps(
uint256 _depegThresholdBps,
uint256 _maximalDepegThresholdBps
) external;
/**
* @notice Previews the expected output of a swap operation without executing it
* @dev Calculates both direct token output and potential IOU tokens that would be minted
* Used for frontend display and slippage calculations
* @param _vault The vault address that would execute the swap
* @param _from The input token address
* @param _to The output token address
* @param _amountIn The amount of input tokens to preview
* @return amountOut The expected amount of output tokens
* @return ious The expected amount of IOU tokens (after fees)
*/
function previewSwap(
address _vault,
address _from,
address _to,
uint256 _amountIn,
bool _receiveIOU
) external view returns (uint256 amountOut, uint256 ious);
/**
* @notice Executes a token swap through the specified vault with IOU support
* @dev Transfers input tokens from caller, executes vault liquidity swap, and handles IOU redemption
* Can either return IOU tokens directly or automatically swap them for underlying via Curve
* @param _receiver The address that will receive the output tokens and/or IOUs
* @param _vault The vault address to execute the swap through
* @param _from The input token address to swap from
* @param _to The output token address to swap to
* @param _amountIn The amount of input tokens to swap
* @param _minAmountOut Minimum total output expected (slippage protection)
* @param _receiveIOU Whether to receive IOU tokens directly (true) or swap them via Curve (false)
* @return amountOut The actual amount of output tokens received
* @return ious The amount of IOU tokens received (0 if _receiveIOU is false)
*/
function swap(
address _receiver,
address _vault,
address _from,
address _to,
uint256 _amountIn,
uint256 _minAmountOut,
bool _receiveIOU
) external returns (uint256 amountOut, uint256 ious);
/**
* @notice Redeems IOU tokens for underlying tokens when vault conditions allow
* @dev Burns caller's IOU tokens and transfers underlying tokens to receiver
* Only works when vault is balanced and token price has recovered sufficiently
* @param _receiver The address that will receive the underlying tokens
* @param _vault The vault that manages the IOU tokens and underlying liquidity
* @param _token The underlying token address that the IOUs represent
* @param _amount The amount of IOU tokens to redeem for underlying tokens
*/
function redeemIOU(
address _receiver,
address _vault,
address _token,
uint256 _amount
) external;
}
project/contracts/interfaces/IClearVault.sol
// SPDX-License-Identifier: MIT
//████████╗██████╗ ███████╗██╗ ██╗███████╗███████╗
//╚══██╔══╝██╔══██╗██╔════╝██║ ██║██╔════╝██╔════╝
// ██║ ██████╔╝█████╗ ██║ ██║█████╗ █████╗
// ██║ ██╔══██╗██╔══╝ ╚██╗ ██╔╝██╔══╝ ██╔══╝
// ██║ ██║ ██║███████╗ ╚████╔╝ ███████╗███████╗
// ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═══╝ ╚══════╝╚══════╝
pragma solidity ^0.8.24;
import "@openzeppelin/contracts/interfaces/IERC20.sol";
import "@openzeppelin/contracts/interfaces/IERC20Metadata.sol";
/**
* @title IClearVault
* @notice Interface for Clear protocol's multi-token yield vault
* @dev Extends ERC20 with multi-token vault functionality and swap integration
* @author Clear Protocol Team
*/
interface IClearVault is IERC20, IERC20Metadata {
error InvalidAmount();
error InvalidInput();
error NoTokenDecimals(address token);
error UnknownToken(address token);
error BadAdapterConfiguration();
error InvalidTokenDecimals(address token, uint8 decimals);
error SwapExceedMaximalExposure();
error CurvePoolNotSet();
error UnknownRebalanceSwapError();
error TokenAlreadyInitialized();
error RebalanceSpreadTooHigh(uint256 amountIn, uint256 amountOut);
/**
* @dev Attempted to deposit more assets than the max amount for `receiver`.
*/
error ClearVaultExceededMaxDeposit(address receiver, uint256 assets, uint256 max);
/**
* @dev Attempted to mint more shares than the max amount for `receiver`.
*/
error ClearVaultExceededMaxMint(address receiver, uint256 shares, uint256 max);
/**
* @dev Attempted to withdraw more assets than the max amount for `receiver`.
*/
error ClearVaultExceededMaxWithdraw(address owner, uint256 assets, uint256 max);
/**
* @dev Attempted to redeem more shares than the max amount for `receiver`.
*/
error ClearVaultExceededMaxRedeem(address owner, uint256 shares, uint256 max);
/// @notice Emitted when assets are deposited into the vault
event Deposit(address indexed token, address indexed sender, address indexed owner, uint256 assets, uint256 shares);
/// @notice Emitted when assets are withdrawn from the vault
event Withdraw(
address indexed token,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/// @notice Emitted when the vault proxy is initialized
event VaultInitialized(
address _initialAuthority,
string _name,
string _symbol,
address _tokensCurvePool,
address[] _tokens
);
/// @notice Emitted when a new token is added to the vault's allowed list
event TokenAdded(address token);
/// @notice Emitted when a token's yield adapter is replaced
event AdapterChanged(address token, address newAdapter);
/// @notice Emitted when a token's desired or maximum exposure limits are updated
event TokenExposureConfigurationUpdated(address token, uint256 newDesiredExposureBps, uint256 newMaximalExposureBps);
/// @notice Emitted when the maximum rebalance slippage tolerance is updated
event MaximalRebalanceBpsSpreadUpdated(uint256 newSpread);
/// @notice Emitted when the maximum deviation from desired exposure is updated
event DesiredExposureMaximalBpsSpreadUpdated(uint256 newSpread);
/// @notice Emitted when the IOU minting fee is updated
event IouFeeBpsUpdated(uint256 lpFee, uint256 treasuryFee);
/// @notice Emitted when the Curve IOU meta pool address is updated for a token
event IouCurveMetaPoolUpdated(address token, address pool);
/// @notice Emitted when a rebalance swap between two tokens is executed
event LiquidityRebalanceExecuted(address from, address to, uint256 amountIn, uint256 amountOut);
/// @notice Emitted when underlying tokens are directly wrapped into IOU tokens
event ClearIOUWrapped(address indexed token, address indexed sender, address indexed receiver, uint256 amount);
/// @notice Emitted when a liquidity swap is executed (potentially with IOU minting)
event LiquiditySwapExecuted(
address indexed from,
address indexed to,
address receiver,
uint256 amountIn,
uint256 tokenAmountOut,
uint256 iouAmountOut,
uint256 iouTreasuryFee,
uint256 iouLpFee
);
/// @notice Emitted when a token is fully initialized with its IOU token, Curve pool, and adapter
event TokenInitialized(
address indexed token,
address iouCurveMetaPool,
address iou,
address adapter,
uint256 desiredExposureBps,
uint256 maxExposureBps
);
/// @notice Internal per-token storage entry
struct Token {
bool enabled; ///< Whether this token has been added to the vault
bool initialized; ///< Whether initializeToken() has been called for this token
address iou; ///< IOU token proxy address
address iouCurveMetaPool; ///< Curve meta pool address for IOU/token trading
uint256 tokensCurvePoolIndex; ///< Index of this token in the Curve plain pool
address adapter; ///< ERC4626 yield adapter address (address(0) if none)
uint256 maxExposureBps; ///< Maximum allowed exposure in basis points
uint256 desiredExposureBps; ///< Target exposure in basis points
uint256 emitedIou; ///< Total outstanding IOU tokens (net of redemptions)
uint8 decimals; ///< Native decimal count of this token
}
/// @notice Read-only view of a token's current state, returned by details()
struct TokenDetails {
address addr; ///< Token contract address
address iou; ///< IOU token proxy address
address iouCurveMetaPool; ///< Curve meta pool address for IOU/token trading
address adapter; ///< ERC4626 yield adapter address
uint256 maxExposureBps; ///< Maximum allowed exposure in basis points
uint256 desiredExposureBps; ///< Target exposure in basis points
uint256 emitedIou; ///< Total outstanding IOU tokens
uint256 balance; ///< Current token assets (adapter balance minus IOUs)
uint256 exposure; ///< Current exposure in basis points
uint8 decimals; ///< Native decimal count of this token
}
/// @notice Top-level vault configuration storage
struct Configuration {
address[] allowedTokens; ///< Ordered list of all vault tokens
mapping(address => Token) tokens; ///< Per-token configuration and state
address tokensCurvePool; ///< Curve plain pool shared by all vault tokens
uint256 iouTreasuryFeeBps; ///< Treasury fee on IOU minting (basis points)
uint256 iouLpFeeBps; ///< LP fee on IOU minting (basis points)
uint256 maximumRebalanceBpsSpread; ///< Max slippage allowed during rebalancing
uint256 desiredExposureMaximalBpsSpread; ///< Max deviation from desired exposure
}
/**
* @notice Initializes the vault proxy with access control, ERC20 metadata, and initial tokens
* @param _initialAuthority The access control authority contract address
* @param _name The name for the vault's ERC20 share token
* @param _symbol The symbol for the vault's ERC20 share token
* @param _tokensCurvePool The Curve plain pool address for multi-token swaps
* @param _tokens Array of ERC20 token addresses to support in this vault
*/
function initialize(
address _initialAuthority,
string memory _name,
string memory _symbol,
address _tokensCurvePool,
address[] memory _tokens
) external;
/**
* @notice Completes token setup by associating its IOU token, Curve meta pool, and adapter
* @param _token The underlying token address to initialize
* @param _iou The IOU token proxy address
* @param _iouCurveMetaPool The Curve meta pool address for IOU/token trading
* @param _adapter The ERC4626 yield adapter address
* @param _desiredExposureBps Desired exposure in basis points (10000 = 100%)
* @param _maxExposureBps Maximum allowed exposure in basis points (10000 = 100%)
*/
function initializeToken(
address _token,
address _iou,
address _iouCurveMetaPool,
address _adapter,
uint256 _desiredExposureBps,
uint256 _maxExposureBps
) external;
/// @notice Returns the Curve plain pool address shared by all vault tokens
function tokensCurvePool() external view returns (address);
/// @notice Returns the zero-based index of a token in the Curve plain pool
/// @param _token The token address to query (must be enabled)
function tokensCurvePoolIndexOf(address _token) external view returns (uint256);
/// @notice Returns the Curve IOU meta pool address for a given token
/// @param _token The underlying token address (must be enabled)
function tokenCurveMetaPool(address _token) external view returns (address);
/**
* @notice Changes the yield adapter for a specific token
* @dev Withdraws all funds from current adapter and deposits into new one
* Only callable by factory for enabled tokens
* @param _token The token whose adapter to change
* @param _newAdapter The new adapter contract address
*/
function changeAdapter(address _token, address _newAdapter) external;
/**
* @notice Updates exposure configuration for a specific token
* @dev Sets the desired and maximum exposure limits for vault rebalancing
* @param _token The token address to configure
* @param _newDesiredExposureBps New desired exposure in basis points (10000 = 100%)
* @param _newMaximalExposureBps New maximum exposure in basis points (10000 = 100%)
*/
function setTokenExposureConfiguration(
address _token,
uint256 _newDesiredExposureBps,
uint256 _newMaximalExposureBps
) external;
/**
* @notice Returns the maximum exposure limit for a specific token
* @dev Gets the maximum percentage of vault assets that can be this token
* @param _token The token address to query
* @return desiredExposureBps Desired exposure in basis points (10000 = 100%)
* @return maxExposureBps Maximum exposure in basis points (10000 = 100%)
*/
function exposureConfigurationOf(address _token) external view returns (uint256 desiredExposureBps, uint256 maxExposureBps);
/**
* @notice Returns the specified token exposure
* @dev Gets the current exposure of specific token
* @param _token The token address to query
* @return exposure Current exposure in basis points (10000 = 100%)
*/
function exposureOf(address _token) external view returns (uint256 exposure);
/**
* @notice Updates the maximum allowed slippage for rebalancing operations
* @dev Sets tolerance for price impact during automated rebalancing swaps
* @param _newMaximumRebalanceBpsSpread Maximum spread in basis points (10000 = 100%)
*/
function setMaximumRebalanceBpsSpread(uint256 _newMaximumRebalanceBpsSpread) external;
/**
* @notice Updates the maximum spread from desired exposure before rebalancing triggers
* @dev Sets the tolerance for exposure deviation that determines when vault is balanced
* @param _newDesiredExposureMaximalBpsSpread Maximum deviation from desired exposure in basis points
*/
function setDesiredExposureMaximalBpsSpread(uint256 _newDesiredExposureMaximalBpsSpread) external;
/**
* @notice Returns the maximum allowed slippage for rebalancing operations
* @dev Gets the current tolerance for price impact during rebalancing
* @return The maximum spread in basis points
*/
function maximumRebalanceBpsSpread() external view returns (uint256);
/**
* @notice Returns the maximum spread from desired exposure before rebalancing triggers
* @dev Gets the current tolerance for exposure deviation
* @return The maximum deviation from desired exposure in basis points
*/
function desiredExposureMaximalBpsSpread() external view returns (uint256);
/**
* @notice Updates the fee charged when minting IOU tokens
* @dev Sets the fee percentage taken from IOU minting operations
* @param _lpFee New LP fee in basis points (10000 = 100%)
* @param _treasuryFee New treasury fee in basis points (10000 = 100%)
*/
function setIouFeeBps(
uint256 _lpFee,
uint256 _treasuryFee
) external;
/**
* @notice Returns the current IOU minting fee
* @dev Gets the fee percentage charged when minting IOU tokens
* @return lpFee The current lp fee in basis points
* @return treasuryFee The current treasury fee in basis points
*/
function iouFeeBps() external view returns (uint256 lpFee, uint256 treasuryFee);
/**
* @notice Checks if the vault's token exposures are within the desired balance range
* @dev Iterates through all allowed tokens and verifies their exposure is within maximal spread from desired exposure
* @return true if all token exposures are balanced within the acceptable range, false otherwise
*/
function isBalanced() external view returns (bool);
/**
* @notice Returns the IOU token address for a given underlying token
* @dev Gets the corresponding IOU token contract address
* @param _token The underlying token address
* @return The IOU token contract address
*/
function iouOf(address _token) external returns (address);
/**
* @notice Returns the Curve pool address for a token's IOU trading
* @dev Gets the Curve liquidity pool for token/IOU swaps
* @param _token The underlying token address
* @return The Curve pool contract address
*/
function iouCurveMetaPoolOf(address _token) external view returns (address);
/**
* @notice Returns comprehensive vault configuration and token information
* @dev Aggregates vault settings, fees, and detailed information about all enabled tokens
* Provides a complete view of vault state for external consumers
* @return iouTreasuryFeeBps The current IOU minting treasury fee in basis points
* @return iouLpFeeBps The current IOU minting LP fee in basis points
* @return maximumRebalanceBpsSpread Maximum allowed slippage during rebalancing in basis points
* @return desiredExposureMaximalBpsSpread Maximum deviation from desired exposure before rebalancing
* @return totalAssets Total value of all assets managed by the vault
* @return tokens Array of detailed information for all vault tokens including balances and configurations
*/
function details() external view returns (
uint256 iouTreasuryFeeBps,
uint256 iouLpFeeBps,
uint256 maximumRebalanceBpsSpread,
uint256 desiredExposureMaximalBpsSpread,
uint256 totalAssets,
TokenDetails[] memory tokens
);
/**
* @notice Executes a liquidity swap between tokens with optional IOU minting
* @dev Performs token swap and optionally mints IOU tokens when liquidity is insufficient
* Validates exposure limits and charges fees on IOU minting
* @param _receiver Address to receive the output tokens and IOUs
* @param _from Input token address
* @param _to Output token address
* @param _amountIn Amount of input tokens
* @param _amountOut Amount of output tokens to transfer
* @param _amountIou Amount of IOU tokens to mint (if any)
* @return iousReceived Actual IOU tokens received after fees
*/
function swapLiquidity(
address _receiver,
address _from,
address _to,
uint256 _amountIn,
uint256 _amountOut,
uint256 _amountIou
) external returns (
uint256 iousReceived
);
/**
* @notice Redeems IOU tokens for underlying tokens
* @dev Burns IOU tokens and transfers underlying tokens to receiver
* Updates emitted IOU tracking
* @param _sender Address holding the IOU tokens to burn
* @param _receiver Address to receive the underlying tokens
* @param _token The underlying token address
* @param _amount Amount of IOU tokens to redeem
*/
function redeemIOU(
address _sender,
address _receiver,
address _token,
uint256 _amount
) external;
/**
* @notice Executes a rebalancing operation between two tokens
* @dev Performs token swap using external contracts to rebalance vault exposure
* Validates slippage against maximum spread
* @param _from Token to sell
* @param _to Token to buy
* @param _approval Contract to approve for token spending
* @param _target Contract to execute the swap
* @param _amount Amount of tokens to swap
* @param _payload Encoded call data for the swap operation
*/
function rebalance(
address _from,
address _to,
address _approval,
address _target,
uint256 _amount,
bytes calldata _payload
) external;
/**
* @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
*
* - MUST be an ERC-20 token contract.
* - MUST NOT revert.
*/
function tokens() external view returns (address[] memory assets);
/**
* @dev Returns the total amount of the underlying asset that is “managed” by Vault.
*
* - SHOULD include any compounding that occurs from yield.
* - MUST be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT revert.
*/
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToShares(address token, uint256 assets) external view returns (uint256 shares);
/**
* @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToAssets(address token, uint256 shares) external view returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
* through a deposit call.
*
* - MUST return a limited value if receiver is subject to some deposit limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
* - MUST NOT revert.
*/
function maxDeposit(address token, address receiver) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
* call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
* in the same transaction.
* - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
* deposit would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewDeposit(address token, uint256 assets) external view returns (uint256 shares);
/**
* @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* deposit execution, and are accounted for during deposit.
* - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(address token, uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
* - MUST return a limited value if receiver is subject to some mint limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
* - MUST NOT revert.
*/
function maxMint(address token, address receiver) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
* in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
* same transaction.
* - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
* would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by minting.
*/
function previewMint(address token, uint256 shares) external view returns (uint256 assets);
/**
* @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
* execution, and are accounted for during mint.
* - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(address token, uint256 shares, address receiver) external returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, through a withdraw call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxWithdraw(address token, address owner) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
* called
* in the same transaction.
* - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
* the withdrawal would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewWithdraw(address token, uint256 assets) external view returns (uint256 shares);
/**
* @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* withdraw execution, and are accounted for during withdraw.
* - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function withdraw(address token, uint256 assets, address receiver, address owner) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
* through a redeem call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxRedeem(address token, address owner) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
* in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
* same transaction.
* - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
* redemption would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by redeeming.
*/
function previewRedeem(address token, uint256 shares) external view returns (uint256 assets);
/**
* @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* redeem execution, and are accounted for during redeem.
* - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function redeem(address token, uint256 shares, address receiver, address owner) external returns (uint256 assets);
}
project/contracts/interfaces/external/ICurveStableSwapNG.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
interface ICurveStableSwapNG {
function coins(uint256 index) external returns (address);
function BASE_N_COINS() external view returns (uint256);
function BASE_COINS(uint256 index) external view returns (address);
function get_dy(
int128 i,
int128 j,
uint256 dx
) external returns (uint256 amountOut);
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
address receiver
) external returns (uint256 amountOut);
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external returns (uint256 amountOut);
function exchange_received(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
address receiver
) external returns (uint256 amountOut);
function exchange_received(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external returns (uint256 amountOut);
function get_dy_underlying(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256 amountOut);
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
address receiver
) external returns (uint256 amountOut);
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external returns (uint256 amountOut);
function add_liquidity(
uint256[] memory amounts,
uint256 minMintAmount
) external returns (uint256 amountOut);
function add_liquidity(
uint256[2] memory amounts,
uint256 minMintAmount
) external returns (uint256 amountOut);
}
Compiler settingsShow
{
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"project/:@openzeppelin/contracts-upgradeable/=npm/@openzeppelin/[email protected]/",
"project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/",
"project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/",
"project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/",
"project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/",
"project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/",
"project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.