Verified contractExactMIT
ContainerLocal
Address0x226808fca1cff3fdebc13286d0109b13c8b0125a
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 5 runs
- EVM version
- prague
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,442,156
- Creation transaction
- 0xd2d2b9deb2…aed9d699e4
25 files
- contracts/ContainerLocal.solmain9.82 KB
- contracts/Container.sol7.46 KB
- contracts/StrategyContainer.sol17.39 KB
- contracts/interfaces/IContainer.sol3.83 KB
- contracts/interfaces/IContainerLocal.sol4.34 KB
- contracts/interfaces/IStrategyContainer.sol8.65 KB
- contracts/interfaces/IStrategyTemplate.sol10.99 KB
- contracts/interfaces/ISwapRouter.sol5.73 KB
- contracts/interfaces/IVault.sol25.09 KB
- contracts/libraries/EnumerableAddressSetExtended.sol1.01 KB
- contracts/libraries/Errors.sol1.21 KB
- lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol8.28 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol8.91 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol1.19 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol3.86 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol4.51 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol1.18 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/access/IAccessControl.sol3.34 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol192 B
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol181 B
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol9.39 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol870 B
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol12.89 KB
contracts/ContainerLocal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Container} from "./Container.sol";
import {StrategyContainer} from "./StrategyContainer.sol";
import {IContainer} from "./interfaces/IContainer.sol";
import {IContainerLocal} from "./interfaces/IContainerLocal.sol";
import {IStrategyContainer} from "./interfaces/IStrategyContainer.sol";
import {IVault} from "./interfaces/IVault.sol";
import {Errors} from "./libraries/Errors.sol";
contract ContainerLocal is StrategyContainer, IContainerLocal {
using SafeERC20 for IERC20;
ContainerLocalStatus public status;
uint256 public registeredWithdrawShareAmount;
constructor() {
_disableInitializers();
}
function initialize(
ContainerInitParams memory containerParams,
StrategyContainerInitParams calldata strategyContainerParams
) public initializer {
__Container_init(containerParams);
__StrategyContainer_init(strategyContainerParams);
IERC20(notion).forceApprove(vault, type(uint256).max);
}
// ---- Container logic ----
/// @inheritdoc IContainer
function containerType() external pure override returns (ContainerType) {
return ContainerType.Local;
}
// ---- Vault interaction ----
/// @inheritdoc IContainerLocal
function registerDepositRequest(
uint256 amount
) external whenNotPaused nonReentrant notResolvingEmergency notInReshufflingMode onlyVault {
require(status == ContainerLocalStatus.Idle, Errors.IncorrectContainerStatus());
require(amount > 0, Errors.ZeroAmount());
status = ContainerLocalStatus.DepositRequestRegistered;
IERC20(notion).safeTransferFrom(vault, address(this), amount);
emit DepositRequestRegistered(amount);
}
/// @inheritdoc IContainerLocal
function registerWithdrawRequest(
uint256 amount
) external whenNotPaused nonReentrant notResolvingEmergency notInReshufflingMode onlyVault {
require(status == ContainerLocalStatus.Idle, Errors.IncorrectContainerStatus());
require(amount > 0, Errors.ZeroAmount());
status = ContainerLocalStatus.WithdrawalRequestRegistered;
registeredWithdrawShareAmount = amount;
emit WithdrawalRequestRegistered(amount);
}
/// @inheritdoc IContainerLocal
function reportDeposit()
external
whenNotPaused
nonReentrant
notResolvingEmergency
notInReshufflingMode
onlyRole(OPERATOR_ROLE)
{
require(status == ContainerLocalStatus.AllStrategiesEntered, Errors.IncorrectContainerStatus());
require(_validateWhitelistedTokensBeforeReport(true, true), WhitelistedTokensOnBalance());
(uint256 nav0, uint256 nav1) = getTotalNavs();
status = ContainerLocalStatus.Idle;
_strategyEnterBitmask = 0;
uint256 remainder = IERC20(notion).balanceOf(address(this));
IVault(vault).reportDeposit(IVault.ContainerReport({nav0: nav0, nav1: nav1}), remainder);
emit DepositReported(nav0, nav1, remainder);
}
/// @inheritdoc IContainerLocal
function reportWithdrawal()
external
whenNotPaused
nonReentrant
notResolvingEmergency
notInReshufflingMode
onlyRole(OPERATOR_ROLE)
{
require(status == ContainerLocalStatus.AllStrategiesExited, Errors.IncorrectContainerStatus());
status = ContainerLocalStatus.Idle;
registeredWithdrawShareAmount = 0;
_strategyExitBitmask = 0;
require(_hasOnlyNotionToken(), WhitelistedTokensOnBalance());
uint256 notionAmount = IERC20(notion).balanceOf(address(this));
IVault(vault).reportWithdraw(notionAmount);
emit WithdrawalReported(notionAmount);
}
// ---- Strategy management logic ----
/// @inheritdoc IStrategyContainer
function addStrategy(
address strategy,
address[] calldata inputTokens,
address[] calldata outputTokens
) external nonReentrant notResolvingEmergency onlyInReshufflingMode onlyRole(RESHUFFLING_MANAGER_ROLE) {
require(status == ContainerLocalStatus.Idle, Errors.IncorrectContainerStatus());
_addStrategy(strategy, inputTokens, outputTokens);
}
/// @inheritdoc IStrategyContainer
function removeStrategy(
address strategy
) external nonReentrant notResolvingEmergency onlyInReshufflingMode onlyRole(RESHUFFLING_EXECUTOR_ROLE) {
require(status == ContainerLocalStatus.Idle, Errors.IncorrectContainerStatus());
_removeStrategy(strategy);
}
// ---- Enter strategy logic ----
/// @inheritdoc IContainerLocal
function enterStrategy(
address strategy,
uint256[] calldata inputAmounts,
uint256 minNavDelta
) external whenNotPaused nonReentrant notInReshufflingMode onlyRole(OPERATOR_ROLE) {
require(status == ContainerLocalStatus.DepositRequestRegistered, Errors.IncorrectContainerStatus());
_enterStrategy(strategy, inputAmounts, minNavDelta);
if (_allStrategiesEntered()) {
status = ContainerLocalStatus.AllStrategiesEntered;
emit AllStrategiesEntered();
}
}
/// @inheritdoc IContainerLocal
function enterStrategyMultiple(
address[] calldata strategies,
uint256[][] calldata inputAmounts,
uint256[] calldata minNavDelta
) external whenNotPaused nonReentrant notInReshufflingMode onlyRole(OPERATOR_ROLE) {
require(status == ContainerLocalStatus.DepositRequestRegistered, Errors.IncorrectContainerStatus());
uint256 length = strategies.length;
require(length > 0 && length <= getStrategiesNumber(), Errors.InvalidArrayLength());
require(length == inputAmounts.length, Errors.ArrayLengthMismatch());
require(length == minNavDelta.length, Errors.ArrayLengthMismatch());
for (uint256 i = 0; i < length; ++i) {
_enterStrategy(strategies[i], inputAmounts[i], minNavDelta[i]);
}
if (_allStrategiesEntered()) {
status = ContainerLocalStatus.AllStrategiesEntered;
emit AllStrategiesEntered();
}
}
// ---- Exit strategy logic ----
/// @inheritdoc IContainerLocal
function exitStrategy(
address strategy,
uint256 maxNavDelta
) external whenNotPaused nonReentrant notInReshufflingMode onlyRole(OPERATOR_ROLE) {
require(status == ContainerLocalStatus.WithdrawalRequestRegistered, Errors.IncorrectContainerStatus());
uint256 registeredShareAmountCached = registeredWithdrawShareAmount;
require(registeredShareAmountCached > 0, NoSharesRegisteredForExit());
_exitStrategy(strategy, registeredShareAmountCached, maxNavDelta);
if (_allStrategiesExited()) {
status = ContainerLocalStatus.AllStrategiesExited;
emit AllStrategiesExited();
}
}
/// @inheritdoc IContainerLocal
function exitStrategyMultiple(
address[] calldata strategies,
uint256[] calldata maxNavDeltas
) external whenNotPaused nonReentrant notInReshufflingMode onlyRole(OPERATOR_ROLE) {
require(status == ContainerLocalStatus.WithdrawalRequestRegistered, Errors.IncorrectContainerStatus());
uint256 length = strategies.length;
require(length > 0 && length <= getStrategiesNumber(), Errors.InvalidArrayLength());
require(length == maxNavDeltas.length, Errors.ArrayLengthMismatch());
uint256 registeredShareAmountCached = registeredWithdrawShareAmount;
require(registeredShareAmountCached > 0, NoSharesRegisteredForExit());
for (uint256 i = 0; i < length; ++i) {
_exitStrategy(strategies[i], registeredShareAmountCached, maxNavDeltas[i]);
}
if (_allStrategiesExited()) {
status = ContainerLocalStatus.AllStrategiesExited;
emit AllStrategiesExited();
}
}
function _getCurrentBatchType() internal view override returns (CurrentBatchType) {
ContainerLocalStatus statusCached = status;
if (statusCached == ContainerLocalStatus.Idle) {
return CurrentBatchType.NoBatch;
}
if (
statusCached == ContainerLocalStatus.DepositRequestRegistered ||
statusCached == ContainerLocalStatus.AllStrategiesEntered
) {
return CurrentBatchType.DepositBatch;
}
if (
statusCached == ContainerLocalStatus.WithdrawalRequestRegistered ||
statusCached == ContainerLocalStatus.AllStrategiesExited
) {
return CurrentBatchType.WithdrawBatch;
}
revert Errors.IncorrectContainerStatus();
}
/// @inheritdoc IContainerLocal
function withdrawToReshufflingGateway(
address[] memory tokens,
uint256[] memory amounts
) external nonReentrant notResolvingEmergency onlyInReshufflingMode onlyRole(RESHUFFLING_EXECUTOR_ROLE) {
uint256 length = tokens.length;
require(length > 0, Errors.ZeroArrayLength());
require(length == amounts.length, Errors.ArrayLengthMismatch());
address reshufflingGatewayCached = reshufflingGateway;
require(reshufflingGatewayCached != address(0), Errors.ZeroAddress());
for (uint256 i = 0; i < length; ++i) {
address token = tokens[i];
uint256 amount = amounts[i];
require(_isTokenWhitelisted(token), NotWhitelistedToken(token));
if (amount > 0) {
IERC20(token).safeTransfer(reshufflingGatewayCached, amount);
}
}
}
}
contracts/Container.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IContainer} from "./interfaces/IContainer.sol";
import {ISwapRouter} from "./interfaces/ISwapRouter.sol";
import {Errors} from "./libraries/Errors.sol";
abstract contract Container is
Initializable,
AccessControlUpgradeable,
PausableUpgradeable,
ReentrancyGuardUpgradeable,
IContainer
{
using EnumerableSet for EnumerableSet.AddressSet;
using SafeERC20 for IERC20;
bytes32 internal constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
bytes32 internal constant TOKEN_MANAGER_ROLE = keccak256("TOKEN_MANAGER_ROLE");
bytes32 internal constant EMERGENCY_PAUSER_ROLE = keccak256("EMERGENCY_PAUSER_ROLE");
address public vault;
address public notion;
address public swapRouter;
EnumerableSet.AddressSet private _whitelistedTokens;
mapping(address => uint256) private _whitelistedTokensDustThresholds;
modifier onlyVault() {
require(msg.sender == vault, Errors.Unauthorized());
_;
}
function __Container_init(ContainerInitParams memory params) internal onlyInitializing {
__AccessControl_init();
__Pausable_init();
__ReentrancyGuard_init();
require(params.vault != address(0), Errors.ZeroAddress());
require(params.notion != address(0), Errors.ZeroAddress());
require(params.emergencyPauser != address(0), Errors.ZeroAddress());
require(params.tokenManager != address(0), Errors.ZeroAddress());
vault = params.vault;
notion = params.notion;
_whitelistedTokens.add(notion);
_setSwapRouter(params.swapRouter);
_grantRole(DEFAULT_ADMIN_ROLE, params.defaultAdmin);
_grantRole(OPERATOR_ROLE, params.operator);
_grantRole(EMERGENCY_PAUSER_ROLE, params.emergencyPauser);
_grantRole(TOKEN_MANAGER_ROLE, params.tokenManager);
}
// ---- Token management logic ----
/// @inheritdoc IContainer
function isTokenWhitelisted(address token) external view returns (bool) {
return _isTokenWhitelisted(token);
}
/// @inheritdoc IContainer
function whitelistToken(address token) external whenNotPaused onlyRole(TOKEN_MANAGER_ROLE) {
require(token != address(0), Errors.ZeroAddress());
require(_whitelistedTokens.add(token), AlreadyWhitelistedToken());
IERC20(token).forceApprove(swapRouter, type(uint256).max);
emit TokenWhitelistUpdated(token, true);
}
/// @inheritdoc IContainer
function blacklistToken(address token) external whenNotPaused onlyRole(TOKEN_MANAGER_ROLE) {
require(token != address(0), Errors.ZeroAddress());
require(_whitelistedTokens.remove(token), NotWhitelistedToken(token));
_whitelistedTokensDustThresholds[token] = 0;
IERC20(token).forceApprove(swapRouter, 0);
emit TokenWhitelistUpdated(token, false);
}
/// @inheritdoc IContainer
function setWhitelistedTokenDustThreshold(
address token,
uint256 threshold
) external whenNotPaused onlyRole(TOKEN_MANAGER_ROLE) {
require(token != address(0), Errors.ZeroAddress());
require(threshold > 0, Errors.ZeroAmount());
require(_whitelistedTokens.contains(token), NotWhitelistedToken(token));
_whitelistedTokensDustThresholds[token] = threshold;
emit WhitelistedTokenDustThresholdUpdated(token, threshold);
}
function _isTokenWhitelisted(address token) internal view returns (bool) {
return _whitelistedTokens.contains(token);
}
function _validateWhitelistedTokensBeforeReport(bool ignoreNotion, bool ignoreDust) internal view returns (bool) {
uint256 length = _whitelistedTokens.length();
for (uint256 i = 0; i < length; i++) {
address token = _whitelistedTokens.at(i);
if (ignoreNotion && token == notion) {
continue;
}
uint256 dustThreshold = !ignoreDust ? 0 : _whitelistedTokensDustThresholds[token];
if (IERC20(token).balanceOf(address(this)) > dustThreshold) {
return false;
}
}
return true;
}
function _hasOnlyNotionToken() internal view returns (bool) {
return _validateWhitelistedTokensBeforeReport(true, true) && IERC20(notion).balanceOf(address(this)) > 0;
}
/// @inheritdoc IContainer
function setSwapRouter(address newSwapRouter) external onlyRole(TOKEN_MANAGER_ROLE) {
_setSwapRouter(newSwapRouter);
}
function _setSwapRouter(address newSwapRouter) internal {
require(newSwapRouter != address(0), Errors.ZeroAddress());
address previousSwapRouter = swapRouter;
swapRouter = newSwapRouter;
if (previousSwapRouter != address(0)) {
_dropApprovesFromWhitelistedTokens(previousSwapRouter);
}
_approveWhitelistedTokens(newSwapRouter);
emit SwapRouterUpdated(previousSwapRouter, newSwapRouter);
}
/// @inheritdoc IContainer
function prepareLiquidity(
ISwapRouter.SwapInstruction[] calldata instructions
) external whenNotPaused onlyRole(OPERATOR_ROLE) {
require(instructions.length > 0, Errors.ZeroArrayLength());
_prepareLiquidity(instructions);
}
function _prepareLiquidity(ISwapRouter.SwapInstruction[] calldata instructions) internal {
uint256 length = instructions.length;
for (uint256 i = 0; i < length; ++i) {
_swap(instructions[i]);
}
}
function _swap(ISwapRouter.SwapInstruction calldata instruction) internal {
require(_isTokenWhitelisted(instruction.tokenIn), NotWhitelistedToken(instruction.tokenIn));
require(_isTokenWhitelisted(instruction.tokenOut), NotWhitelistedToken(instruction.tokenOut));
ISwapRouter(swapRouter).swap(instruction);
}
function _dropApprovesFromWhitelistedTokens(address addr) internal {
uint256 length = _whitelistedTokens.length();
for (uint256 i = 0; i < length; i++) {
address token = _whitelistedTokens.at(i);
IERC20(token).forceApprove(addr, 0);
}
}
function _approveWhitelistedTokens(address addr) internal {
uint256 length = _whitelistedTokens.length();
for (uint256 i = 0; i < length; i++) {
address token = _whitelistedTokens.at(i);
IERC20(token).forceApprove(addr, type(uint256).max);
}
}
/// @inheritdoc IContainer
function pause() external whenNotPaused onlyRole(EMERGENCY_PAUSER_ROLE) {
_pause();
}
/// @inheritdoc IContainer
function unpause() external whenPaused onlyRole(EMERGENCY_PAUSER_ROLE) {
_unpause();
}
uint256[50] private __gap;
}
contracts/StrategyContainer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Container} from "./Container.sol";
import {IStrategyContainer} from "./interfaces/IStrategyContainer.sol";
import {IStrategyTemplate} from "./interfaces/IStrategyTemplate.sol";
import {ISwapRouter} from "./interfaces/ISwapRouter.sol";
import {EnumerableAddressSetExtended} from "./libraries/EnumerableAddressSetExtended.sol";
import {Errors} from "./libraries/Errors.sol";
abstract contract StrategyContainer is Initializable, ReentrancyGuardUpgradeable, Container, IStrategyContainer {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableAddressSetExtended for EnumerableSet.AddressSet;
using SafeERC20 for IERC20;
bytes32 internal constant STRATEGY_MANAGER_ROLE = keccak256("STRATEGY_MANAGER_ROLE");
bytes32 internal constant HARVEST_MANAGER_ROLE = keccak256("HARVEST_MANAGER_ROLE");
bytes32 internal constant RESHUFFLING_MANAGER_ROLE = keccak256("RESHUFFLING_MANAGER_ROLE");
bytes32 internal constant RESHUFFLING_EXECUTOR_ROLE = keccak256("RESHUFFLING_EXECUTOR_ROLE");
bytes32 internal constant EMERGENCY_MANAGER_ROLE = keccak256("EMERGENCY_MANAGER_ROLE");
bytes32 internal constant EMERGENCY_EXECUTOR_ROLE = keccak256("EMERGENCY_EXECUTOR_ROLE");
EnumerableSet.AddressSet internal _strategies;
mapping(address => uint256) internal _strategyNav0;
mapping(address => uint256) internal _strategyNav1;
uint256 internal _strategyEnterBitmask;
uint256 internal _strategyExitBitmask;
// @dev Bitmask to track if strategy's nav is unresolved during emergency resolution
// 0: resolved, 1: unresolved
uint256 internal _strategyUnresolvedNavBitmask;
address public reshufflingGateway;
address public treasury;
uint256 public feePct;
address public priceOracle;
uint256 private constant MAX_BPS = 1e18;
uint256 private constant MAX_STRATEGIES = 255;
bool public isReshuffling;
bool public isResolvingEmergency;
modifier notResolvingEmergency() {
require(!isResolvingEmergency, EmergencyResolutionInProgress());
_;
}
modifier notInReshufflingMode() {
require(!isReshuffling, Errors.ReshufflingModeEnabled());
_;
}
modifier onlyInReshufflingMode() {
require(isReshuffling, Errors.ReshufflingModeDisabled());
_;
}
function __StrategyContainer_init(StrategyContainerInitParams memory params) internal onlyInitializing {
require(params.roleAddresses.strategyManager != address(0), Errors.ZeroAddress());
require(params.roleAddresses.harvestManager != address(0), Errors.ZeroAddress());
require(params.roleAddresses.reshufflingManager != address(0), Errors.ZeroAddress());
require(params.roleAddresses.reshufflingExecutor != address(0), Errors.ZeroAddress());
require(params.roleAddresses.emergencyManager != address(0), Errors.ZeroAddress());
require(params.roleAddresses.emergencyExecutor != address(0), Errors.ZeroAddress());
_grantRole(STRATEGY_MANAGER_ROLE, params.roleAddresses.strategyManager);
_grantRole(RESHUFFLING_MANAGER_ROLE, params.roleAddresses.reshufflingManager);
_grantRole(RESHUFFLING_EXECUTOR_ROLE, params.roleAddresses.reshufflingExecutor);
_grantRole(HARVEST_MANAGER_ROLE, params.roleAddresses.harvestManager);
_grantRole(EMERGENCY_MANAGER_ROLE, params.roleAddresses.emergencyManager);
_grantRole(EMERGENCY_EXECUTOR_ROLE, params.roleAddresses.emergencyExecutor);
_setReshufflingGateway(params.reshufflingGateway);
_setTreasury(params.treasury);
_setFeePct(params.feePct);
_setPriceOracle(params.priceOracle);
isReshuffling = true;
}
// ---- Configuration ----
/// @inheritdoc IStrategyContainer
function setReshufflingGateway(
address newReshufflingGateway
) external notInReshufflingMode onlyRole(RESHUFFLING_MANAGER_ROLE) {
_setReshufflingGateway(newReshufflingGateway);
}
/// @inheritdoc IStrategyContainer
function setTreasury(address newTreasury) external onlyRole(STRATEGY_MANAGER_ROLE) {
_setTreasury(newTreasury);
}
/// @inheritdoc IStrategyContainer
function setFeePct(uint256 newFeePct) external onlyRole(STRATEGY_MANAGER_ROLE) {
_setFeePct(newFeePct);
}
/// @inheritdoc IStrategyContainer
function setPriceOracle(address newPriceOracle) external onlyRole(STRATEGY_MANAGER_ROLE) {
_setPriceOracle(newPriceOracle);
}
function _setReshufflingGateway(address newReshufflingGateway) internal {
require(newReshufflingGateway != address(0), Errors.ZeroAddress());
address oldReshufflingGateway = reshufflingGateway;
require(oldReshufflingGateway != newReshufflingGateway, Errors.SettingSameValue());
reshufflingGateway = newReshufflingGateway;
emit ReshufflingGatewayUpdated(oldReshufflingGateway, newReshufflingGateway);
}
function _setTreasury(address newTreasury) internal {
require(newTreasury != address(0), Errors.ZeroAddress());
address oldTreasury = treasury;
treasury = newTreasury;
emit TreasuryUpdated(oldTreasury, newTreasury);
}
function _setFeePct(uint256 newFeePct) internal {
require(newFeePct <= MAX_BPS, Errors.IncorrectAmount());
uint256 previousFeePct = feePct;
feePct = newFeePct;
emit FeePctUpdated(previousFeePct, newFeePct);
}
function _setPriceOracle(address newPriceOracle) internal {
require(newPriceOracle != address(0), Errors.ZeroAddress());
address oldPriceOracle = priceOracle;
priceOracle = newPriceOracle;
emit PriceOracleUpdated(oldPriceOracle, priceOracle);
}
// ---- Reshuffling mode management logic ----
/// @inheritdoc IStrategyContainer
function enableReshufflingMode()
external
notResolvingEmergency
notInReshufflingMode
onlyRole(RESHUFFLING_MANAGER_ROLE)
{
require(_getCurrentBatchType() == CurrentBatchType.NoBatch, Errors.IncorrectContainerStatus());
isReshuffling = true;
emit ReshufflingModeEnabled();
}
/// @inheritdoc IStrategyContainer
function disableReshufflingMode()
external
onlyInReshufflingMode
notResolvingEmergency
onlyRole(RESHUFFLING_EXECUTOR_ROLE)
{
require(_getCurrentBatchType() == CurrentBatchType.NoBatch, Errors.IncorrectContainerStatus());
isReshuffling = false;
emit ReshufflingModeDisabled();
}
function prepareLiquidityInReshufflingMode(
ISwapRouter.SwapInstruction[] calldata instructions
) external onlyInReshufflingMode onlyRole(RESHUFFLING_EXECUTOR_ROLE) {
require(instructions.length > 0, Errors.ZeroArrayLength());
_prepareLiquidity(instructions);
}
// ---- Strategies management logic ----
/// @inheritdoc IStrategyContainer
function getStrategies() external view returns (address[] memory) {
return _strategies.values();
}
/// @inheritdoc IStrategyContainer
function getStrategiesNumber() public view returns (uint256) {
return _strategies.length();
}
/// @inheritdoc IStrategyContainer
function isStrategy(address strategy) external view returns (bool) {
return _isStrategy(strategy);
}
function _addStrategy(address strategy, address[] calldata inputTokens, address[] calldata outputTokens) internal {
require(strategy != address(0), Errors.ZeroAddress());
require(_strategies.length() < MAX_STRATEGIES, MaxStrategiesReached());
IStrategyTemplate(strategy).setInputTokens(inputTokens);
IStrategyTemplate(strategy).setOutputTokens(outputTokens);
require(_strategies.add(strategy), StrategyAlreadyExists());
emit StrategyAdded(strategy);
}
function _removeStrategy(address strategy) internal {
require(strategy != address(0), Errors.ZeroAddress());
require(_strategies.remove(strategy), StrategyNotFound());
address[] memory inputTokens = IStrategyTemplate(strategy).getInputTokens();
uint256 length = inputTokens.length;
for (uint256 i = 0; i < length; ++i) {
IERC20(inputTokens[i]).forceApprove(strategy, 0);
}
emit StrategyRemoved(strategy);
}
function _isStrategy(address strategy) private view returns (bool) {
return _strategies.contains(strategy);
}
/// @inheritdoc IStrategyContainer
function getTotalNavs() public view returns (uint256, uint256) {
uint256 totalNav0 = 0;
uint256 totalNav1 = 0;
uint256 length = _strategies.length();
for (uint256 i = 0; i < length; ++i) {
address strategy = _strategies.at(i);
totalNav0 += _strategyNav0[strategy];
totalNav1 += _strategyNav1[strategy];
}
return (totalNav0, totalNav1);
}
// ---- Strategy enter logic ----
function _allStrategiesEntered() internal view returns (bool) {
return _strategyEnterBitmask == (1 << _strategies.length()) - 1;
}
function _enterStrategy(address strategy, uint256[] calldata inputAmounts, uint256 minNavDelta) internal {
require(_isStrategy(strategy), StrategyNotFound());
require(!_isStrategyNavUnresolved(strategy), StrategyNavUnresolved(strategy));
EnterStrategyLocalVars memory vars;
address[] memory inputTokens = IStrategyTemplate(strategy).getInputTokens();
vars.tokenNumber = inputTokens.length;
require(vars.tokenNumber > 0, Errors.ZeroArrayLength());
require(inputAmounts.length == vars.tokenNumber, Errors.ArrayLengthMismatch());
for (uint256 i = 0; i < vars.tokenNumber; ++i) {
require(_isTokenWhitelisted(inputTokens[i]), NotWhitelistedToken(inputTokens[i]));
}
(, vars.strategyIndex) = _strategies.indexOf(strategy);
vars.enterBitmask = _strategyEnterBitmask;
vars.strategyMask = 1 << vars.strategyIndex;
require(vars.enterBitmask & vars.strategyMask == 0, StrategyAlreadyEntered(strategy));
_strategyEnterBitmask = vars.enterBitmask | vars.strategyMask;
vars.nav0 = IStrategyTemplate(strategy).harvest();
_strategyNav0[strategy] = vars.nav0;
for (uint256 i = 0; i < vars.tokenNumber; ++i) {
IERC20(inputTokens[i]).safeIncreaseAllowance(strategy, inputAmounts[i]);
}
uint256[] memory remainingAmounts;
(vars.nav1, vars.hasRemainder, remainingAmounts) = IStrategyTemplate(strategy).enter(inputAmounts, minNavDelta);
_strategyNav1[strategy] = vars.nav1;
require(vars.nav1 > vars.nav0, IncorrectEnterNav(vars.nav0, vars.nav1));
if (vars.hasRemainder) {
require(remainingAmounts.length == vars.tokenNumber, Errors.ArrayLengthMismatch());
for (uint256 i = 0; i < vars.tokenNumber; ++i) {
if (remainingAmounts[i] > 0) {
IERC20(inputTokens[i]).safeTransferFrom(strategy, address(this), remainingAmounts[i]);
}
}
}
emit StrategyEntered(strategy, vars.nav0, vars.nav1, vars.hasRemainder);
}
/// @inheritdoc IStrategyContainer
function enterInReshufflingMode(
address strategy,
uint256[] calldata inputAmounts,
uint256 minNavDelta
) external nonReentrant onlyInReshufflingMode onlyRole(RESHUFFLING_EXECUTOR_ROLE) {
require(_isStrategy(strategy), StrategyNotFound());
require(!_isStrategyNavUnresolved(strategy), StrategyNavUnresolved(strategy));
address[] memory inputTokens = IStrategyTemplate(strategy).getInputTokens();
uint256 tokenNumber = inputTokens.length;
require(tokenNumber > 0, Errors.ZeroArrayLength());
require(tokenNumber == inputAmounts.length, Errors.ArrayLengthMismatch());
uint256 nav0 = IStrategyTemplate(strategy).harvest();
for (uint256 i = 0; i < tokenNumber; ++i) {
IERC20(inputTokens[i]).safeIncreaseAllowance(strategy, inputAmounts[i]);
}
(uint256 nav1, bool hasRemainder, uint256[] memory remainingAmounts) = IStrategyTemplate(strategy).enter(
inputAmounts,
minNavDelta
);
if (hasRemainder) {
uint256 length = remainingAmounts.length;
require(length == inputTokens.length, Errors.ArrayLengthMismatch());
for (uint256 i = 0; i < length; ++i) {
require(_isTokenWhitelisted(inputTokens[i]), NotWhitelistedToken(inputTokens[i]));
IERC20(inputTokens[i]).safeTransferFrom(strategy, address(this), remainingAmounts[i]);
}
}
emit StrategyEntered(strategy, nav0, nav1, hasRemainder);
}
// ---- Strategy exit logic ----
/// @inheritdoc IStrategyContainer
function exitInReshufflingMode(
address strategy,
uint256 share,
uint256 maxNavDelta
) external nonReentrant onlyInReshufflingMode onlyRole(RESHUFFLING_EXECUTOR_ROLE) {
require(share > 0, Errors.ZeroAmount());
require(share <= MAX_BPS, Errors.IncorrectAmount());
require(_isStrategy(strategy), StrategyNotFound());
require(!_isStrategyNavUnresolved(strategy), StrategyNavUnresolved(strategy));
IStrategyTemplate(strategy).harvest();
(address[] memory tokens, uint256[] memory amounts) = IStrategyTemplate(strategy).exit(share, maxNavDelta);
uint256 length = tokens.length;
require(length == amounts.length, Errors.ArrayLengthMismatch());
for (uint256 i = 0; i < length; ++i) {
if (_isTokenWhitelisted(tokens[i])) {
IERC20(tokens[i]).safeTransferFrom(strategy, address(this), amounts[i]);
}
}
emit StrategyExited(strategy, share);
}
function _allStrategiesExited() internal view returns (bool) {
return _strategyExitBitmask == (1 << _strategies.length()) - 1;
}
function _exitStrategy(address strategy, uint256 share, uint256 maxNavDelta) internal {
require(_isStrategy(strategy), StrategyNotFound());
require(!_isStrategyNavUnresolved(strategy), StrategyNavUnresolved(strategy));
(, uint256 strategyIndex) = _strategies.indexOf(strategy);
uint256 mask = 1 << strategyIndex;
require(_strategyExitBitmask & mask == 0, StrategyAlreadyExited(strategy));
_strategyExitBitmask |= mask;
IStrategyTemplate(strategy).harvest();
(address[] memory tokens, uint256[] memory amounts) = IStrategyTemplate(strategy).exit(share, maxNavDelta);
uint256 length = tokens.length;
require(length == amounts.length, Errors.ArrayLengthMismatch());
for (uint256 i = 0; i < length; ++i) {
if (_isTokenWhitelisted(tokens[i])) {
IERC20(tokens[i]).safeTransferFrom(strategy, address(this), amounts[i]);
}
}
emit StrategyExited(strategy, share);
}
// ---- Emergency resolution logic ----
/// @inheritdoc IStrategyContainer
function startEmergencyResolution() external {
require(_isStrategy(msg.sender), StrategyNotFound());
(, uint256 strategyIndex) = _strategies.indexOf(msg.sender);
uint256 mask = 1 << strategyIndex;
_strategyUnresolvedNavBitmask |= mask;
if (!isResolvingEmergency) {
isResolvingEmergency = true;
emit EmergencyResolutionStarted(msg.sender);
}
}
/// @inheritdoc IStrategyContainer
function completeEmergencyResolution() external onlyRole(EMERGENCY_EXECUTOR_ROLE) {
require(isResolvingEmergency, NotResolvingEmergency());
isResolvingEmergency = false;
require(_strategyUnresolvedNavBitmask == 0, EmergencyResolutionNotCompleted(_strategyUnresolvedNavBitmask));
emit EmergencyResolutionCompleted();
}
/// @inheritdoc IStrategyContainer
function resolveStrategyNav(uint256 resolvedNav) external {
require(_isStrategy(msg.sender), StrategyNotFound());
require(_isStrategyNavUnresolved(msg.sender), StrategyNavAlreadyResolved(msg.sender));
(, uint256 strategyIndex) = _strategies.indexOf(msg.sender);
uint256 mask = 1 << strategyIndex;
_strategyUnresolvedNavBitmask &= ~mask;
emit StrategyNavResolved(msg.sender, resolvedNav);
}
function _isStrategyNavUnresolved(address strategy) internal view returns (bool) {
(, uint256 strategyIndex) = _strategies.indexOf(strategy);
uint256 mask = 1 << strategyIndex;
return _strategyUnresolvedNavBitmask & mask != 0;
}
function _getCurrentBatchType() internal view virtual returns (CurrentBatchType);
uint256[50] private __gap;
}
contracts/interfaces/IContainer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {ISwapRouter} from "./ISwapRouter.sol";
interface IContainer {
// ---- Enums ----
enum ContainerType {
Local,
Principal,
Agent
}
// ---- Structs ----
struct ContainerInitParams {
address vault;
address notion;
address defaultAdmin;
address operator;
address emergencyPauser;
address tokenManager;
address swapRouter;
}
// ---- Events ----
event SwapRouterUpdated(address indexed previousSwapRouter, address indexed newSwapRouter);
event TokenWhitelistUpdated(address indexed token, bool isWhitelisted);
event WhitelistedTokenDustThresholdUpdated(address indexed token, uint256 threshold);
// ---- Errors ----
error AlreadyWhitelistedToken();
error NotWhitelistedToken(address token);
error WhitelistedTokensOnBalance();
// ---- Functions ----
/**
* @notice Returns the vault address.
* @return The address of the vault contract
*/
function vault() external view returns (address);
/**
* @notice Returns the notion token address.
* @return The address of the notion token contract
*/
function notion() external view returns (address);
/**
* @notice Returns the swap router address.
* @return The address of the swap router contract
*/
function swapRouter() external view returns (address);
/**
* @notice Returns the container type.
* @return The type of container (Local, Principal, or Agent)
*/
function containerType() external view returns (ContainerType);
/**
* @notice Checks if a token is whitelisted.
* @param token The address of the token to check
* @return True if the token is whitelisted, false otherwise
*/
function isTokenWhitelisted(address token) external view returns (bool);
/**
* @notice Whitelists a token for use in the container.
* @dev Can only be called by accounts with TOKEN_MANAGER_ROLE.
* @param token The address of the token to whitelist
*/
function whitelistToken(address token) external;
/**
* @notice Removes a token from the whitelist.
* @dev Can only be called by accounts with TOKEN_MANAGER_ROLE.
* @param token The address of the token to blacklist
*/
function blacklistToken(address token) external;
/**
* @notice Sets the dust threshold for a whitelisted token.
* @dev Can only be called by accounts with TOKEN_MANAGER_ROLE.
* @param token The address of the whitelisted token
* @param threshold The minimum amount below which the token balance is considered dust
*/
function setWhitelistedTokenDustThreshold(address token, uint256 threshold) external;
/**
* @notice Sets the swap router address.
* @dev Can only be called by accounts with TOKEN_MANAGER_ROLE.
* @param newSwapRouter The address of the new swap router contract
*/
function setSwapRouter(address newSwapRouter) external;
/**
* @notice Prepares liquidity by executing swap instructions.
* @dev Can only be called by accounts with OPERATOR_ROLE. Executes swaps to prepare tokens for strategies.
* @param instructions Array of swap instructions to execute
*/
function prepareLiquidity(ISwapRouter.SwapInstruction[] calldata instructions) external;
/**
* @notice Pauses all state-changing operations in the container.
* @dev Can only be called by accounts with EMERGENCY_PAUSER_ROLE.
*/
function pause() external;
/**
* @notice Unpauses the container and re-enables state-changing operations.
* @dev Can only be called by accounts with EMERGENCY_PAUSER_ROLE.
*/
function unpause() external;
}
contracts/interfaces/IContainerLocal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IStrategyContainer} from "./IStrategyContainer.sol";
interface IContainerLocal is IStrategyContainer {
// ---- Enums ----
enum ContainerLocalStatus {
Idle,
DepositRequestRegistered,
AllStrategiesEntered,
WithdrawalRequestRegistered,
AllStrategiesExited
}
// ---- Events ----
event DepositRequestRegistered(uint256 amount);
event WithdrawalRequestRegistered(uint256 shares);
event DepositReported(uint256 nav0, uint256 nav1, uint256 remainder);
event WithdrawalReported(uint256 notionAmount);
event AllStrategiesEntered();
event AllStrategiesExited();
// ---- Functions ----
/**
* @notice Returns the current status of the container.
* @return The current ContainerLocalStatus
*/
function status() external view returns (ContainerLocalStatus);
/**
* @notice Returns the registered withdrawal share amount.
* @return The share amount registered for withdrawal
*/
function registeredWithdrawShareAmount() external view returns (uint256);
/**
* @notice Registers a deposit request from the vault.
* @dev Can only be called by the vault. Requires container status to be Idle.
* @param amount The amount of notion tokens to deposit
*/
function registerDepositRequest(uint256 amount) external;
/**
* @notice Registers a withdrawal request from the vault.
* @dev Can only be called by the vault. Requires container status to be Idle.
* @param amount The share amount to withdraw
*/
function registerWithdrawRequest(uint256 amount) external;
/**
* @notice Reports deposit results to the vault.
* @dev Can only be called by accounts with OPERATOR_ROLE. Requires status to be AllStrategiesEntered.
*/
function reportDeposit() external;
/**
* @notice Reports withdrawal results to the vault.
* @dev Can only be called by accounts with OPERATOR_ROLE. Requires status to be AllStrategiesExited.
*/
function reportWithdrawal() external;
/**
* @notice Enters a single strategy.
* @dev Can only be called by accounts with OPERATOR_ROLE. Requires appropriate container status.
* @param strategy The address of the strategy to enter
* @param inputAmounts Array of input token amounts
* @param minNavDelta The minimum NAV delta required
*/
function enterStrategy(address strategy, uint256[] calldata inputAmounts, uint256 minNavDelta) external;
/**
* @notice Enters multiple strategies.
* @dev Can only be called by accounts with OPERATOR_ROLE. Requires appropriate container status.
* @param strategies Array of strategy addresses to enter
* @param inputAmounts Array of arrays, where each inner array contains input token amounts for the corresponding strategy
* @param minNavDelta Array of minimum NAV deltas for each strategy
*/
function enterStrategyMultiple(
address[] calldata strategies,
uint256[][] calldata inputAmounts,
uint256[] calldata minNavDelta
) external;
/**
* @notice Exits a single strategy.
* @dev Can only be called by accounts with OPERATOR_ROLE. Requires appropriate container status.
* @param strategy The address of the strategy to exit
* @param maxNavDelta The maximum NAV delta allowed
*/
function exitStrategy(address strategy, uint256 maxNavDelta) external;
/**
* @notice Exits multiple strategies.
* @dev Can only be called by accounts with OPERATOR_ROLE. Requires appropriate container status.
* @param strategies Array of strategy addresses to exit
* @param maxNavDeltas Array of maximum NAV deltas for each strategy
*/
function exitStrategyMultiple(address[] calldata strategies, uint256[] calldata maxNavDeltas) external;
/**
* @notice Withdraws tokens to the reshuffling gateway.
* @dev Can only be called when in reshuffling mode. Can only be called by accounts with RESHUFFLING_EXECUTOR_ROLE.
* @param tokens Array of token addresses to withdraw
* @param amounts Array of token amounts to withdraw
*/
function withdrawToReshufflingGateway(address[] memory tokens, uint256[] memory amounts) external;
}
contracts/interfaces/IStrategyContainer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IContainer} from "./IContainer.sol";
import {ISwapRouter} from "./ISwapRouter.sol";
interface IStrategyContainer is IContainer {
// ---- Enums ----
enum CurrentBatchType {
NoBatch,
DepositBatch,
WithdrawBatch
}
// ---- Structs ----
struct RoleAddresses {
address strategyManager;
address harvestManager;
address reshufflingManager;
address reshufflingExecutor;
address emergencyManager;
address emergencyExecutor;
}
struct StrategyContainerInitParams {
RoleAddresses roleAddresses;
address reshufflingGateway;
address treasury;
uint256 feePct;
address priceOracle;
}
struct NAVReport {
uint256 nav0;
uint256 nav1;
}
struct EnterStrategyLocalVars {
uint256 tokenNumber;
uint256 strategyIndex;
uint256 enterBitmask;
uint256 strategyMask;
uint256 nav0;
uint256 nav1;
bool hasRemainder;
}
// ---- Events ----
event StrategyAdded(address indexed strategy);
event StrategyRemoved(address indexed strategy);
event StrategyEntered(address indexed strategy, uint256 nav0, uint256 nav1, bool hasRemainder);
event StrategyExited(address indexed strategy, uint256 share);
event StrategyInputTokensUpdated(address indexed strategy);
event TreasuryUpdated(address oldTreasury, address newTreasury);
event FeePctUpdated(uint256 oldFeePct, uint256 newFeePct);
event ReshufflingGatewayUpdated(address oldReshufflingGateway, address newReshufflingGateway);
event PriceOracleUpdated(address oldPriceOracle, address newPriceOracle);
event ReshufflingModeEnabled();
event ReshufflingModeDisabled();
event EmergencyResolutionStarted(address strategy);
event EmergencyResolutionCompleted();
event StrategyNavResolved(address indexed strategy, uint256 resolvedNav);
event StrategyOutputTokensUpdated(address indexed strategy);
// ---- Errors ----
error StrategyNotFound();
error StrategyAlreadyHarvested(address strategy);
error StrategyAlreadyExists();
error StrategyAlreadyEntered(address strategy);
error StrategyAlreadyExited(address strategy);
error StrategyHarvestOutdated(address strategy);
error IncorrectNav0();
error NoSharesRegisteredForExit();
error IncorrectEnterNav(uint256 nav0, uint256 nav1);
error StrategyNavUnresolved(address strategy);
error StrategyNavAlreadyResolved(address strategy);
error EmergencyResolutionInProgress();
error NotResolvingEmergency();
error EmergencyResolutionNotCompleted(uint256 strategyUnresolvedNavBitmask);
error MaxStrategiesReached();
// ---- Functions ----
/**
* @notice Returns the treasury address.
* @return The address of the treasury contract
*/
function treasury() external view returns (address);
/**
* @notice Returns the price oracle address.
* @return The address of the price oracle contract
*/
function priceOracle() external view returns (address);
/**
* @notice Returns the fee percentage.
* @return The fee percentage in basis points
*/
function feePct() external view returns (uint256);
/**
* @notice Sets the reshuffling gateway address.
* @dev Can only be called by accounts with RESHUFFLING_MANAGER_ROLE.
* @param newReshufflingGateway The address of the new reshuffling gateway contract
*/
function setReshufflingGateway(address newReshufflingGateway) external;
/**
* @notice Sets the treasury address.
* @dev Can only be called by accounts with STRATEGY_MANAGER_ROLE.
* @param newTreasury The address of the new treasury contract
*/
function setTreasury(address newTreasury) external;
/**
* @notice Sets the fee percentage.
* @dev Can only be called by accounts with STRATEGY_MANAGER_ROLE.
* @param newFeePct The new fee percentage in basis points
*/
function setFeePct(uint256 newFeePct) external;
/**
* @notice Sets the price oracle address.
* @dev Can only be called by accounts with STRATEGY_MANAGER_ROLE.
* @param newPriceOracle The address of the new price oracle contract
*/
function setPriceOracle(address newPriceOracle) external;
/**
* @notice Enables reshuffling mode.
* @dev Can only be called by accounts with RESHUFFLING_MANAGER_ROLE.
*/
function enableReshufflingMode() external;
/**
* @notice Disables reshuffling mode.
* @dev Can only be called by accounts with RESHUFFLING_EXECUTOR_ROLE.
*/
function disableReshufflingMode() external;
/**
* @notice Prepares liquidity in reshuffling mode.
* @dev Can only be called by accounts with RESHUFFLING_EXECUTOR_ROLE.
* @param instructions Swap instructions to execute.
*/
function prepareLiquidityInReshufflingMode(ISwapRouter.SwapInstruction[] calldata instructions) external;
/**
* @notice Returns all registered strategies.
* @return Array of strategy addresses
*/
function getStrategies() external view returns (address[] memory);
/**
* @notice Returns the number of registered strategies.
* @return The number of registered strategies
*/
function getStrategiesNumber() external view returns (uint256);
/**
* @notice Checks if an address is a registered strategy.
* @param strategy The address to check
* @return True if the address is a registered strategy, false otherwise
*/
function isStrategy(address strategy) external view returns (bool);
/**
* @notice Adds a new strategy to the container.
* @dev Can only be called by accounts with RESHUFFLING_MANAGER_ROLE.
* @param strategy The address of the strategy contract to add
* @param inputTokens Array of input token addresses for the strategy
* @param outputTokens Array of output token addresses for the strategy
*/
function addStrategy(address strategy, address[] calldata inputTokens, address[] calldata outputTokens) external;
/**
* @notice Removes a strategy from the container.
* @dev Can only be called by accounts with RESHUFFLING_EXECUTOR_ROLE.
* @param strategy The address of the strategy contract to remove
*/
function removeStrategy(address strategy) external;
/**
* @notice Returns the total NAV values (nav0 and nav1).
* @return nav0 The NAV value before the current batch
* @return nav1 The NAV value after the current batch
*/
function getTotalNavs() external view returns (uint256, uint256);
/**
* @notice Enters a strategy in reshuffling mode.
* @dev Can only be called when in reshuffling mode. Can only be called by accounts with RESHUFFLING_EXECUTOR_ROLE.
* @param strategy The address of the strategy to enter
* @param inputAmounts Array of input token amounts
* @param minNavDelta The minimum NAV delta required
*/
function enterInReshufflingMode(address strategy, uint256[] calldata inputAmounts, uint256 minNavDelta) external;
/**
* @notice Exits a strategy in reshuffling mode.
* @dev Can only be called when in reshuffling mode. Can only be called by accounts with RESHUFFLING_EXECUTOR_ROLE.
* @param strategy The address of the strategy to exit
* @param share The share amount to exit
* @param maxNavDelta The maximum NAV delta allowed
*/
function exitInReshufflingMode(address strategy, uint256 share, uint256 maxNavDelta) external;
/**
* @notice Starts emergency resolution process.
* @dev Can only be called by registered strategies.
*/
function startEmergencyResolution() external;
/**
* @notice Completes emergency resolution process.
* @dev Can only be called when all strategy NAVs have been resolved. Can only be called by accounts with EMERGENCY_MANAGER_ROLE.
*/
function completeEmergencyResolution() external;
/**
* @notice Resolves the NAV for a strategy during emergency resolution.
* @dev Can only be called during emergency resolution. Can only be called by registered strategies.
* @param resolvedNav The resolved NAV value for the strategy
*/
function resolveStrategyNav(uint256 resolvedNav) external;
/**
* @notice Checks if reshuffling mode is enabled.
* @return True if reshuffling mode is enabled, false otherwise
*/
function isReshuffling() external view returns (bool);
}
contracts/interfaces/IStrategyTemplate.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
interface IStrategyTemplate {
// ---- Structs ----
struct EnterLocalVars {
bytes32 currentStateId;
address[] inputTokensCached;
bytes32 enterStateId;
uint256 incomingNav;
uint256 maxSlippageCached;
uint256 enterStateBitmask;
uint256 stateToNavBeforeEnter;
uint256 stateToNavAfterEnter;
uint256[] remainingAmounts;
bool hasRemainder;
}
struct EnterToStateLocalVars {
uint256 toStateBitmask;
bytes32 currentStateId;
uint256 currentStateBitmask;
uint256 stateToNavBeforeEnter;
uint256 stateToNavAfterEnter;
}
struct EnterInEmergencyModeLocalVars {
bytes32 currentStateId;
bytes32 targetStateId;
uint256 currentStateBitmask;
uint256 navBeforeEnter;
uint256 navAfterEnter;
}
struct ExitLocalVars {
bytes32 currentStateId;
uint256 currentStateBitmask;
uint256 currentStateNavBeforeExit;
uint256 expectedNavDelta;
uint256 maxSlippageCached;
uint256 maxAvailableNavDelta;
uint256 currentStateNavAfterExit;
uint256 exitLiquidity;
uint256 tokenShare;
address[] outputTokens;
uint256[] outputAmounts;
uint256[] amountsBeforeExit;
bool hasRemainder;
}
struct HarvestLocalVars {
bytes32 currentStateId;
uint256 currentStateBitmask;
uint256 currentStateNav;
address swapRouter;
address treasury;
uint256 feePct;
}
struct PrepareFundsAfterExitLocalVars {
address[] outputTokens;
uint256[] outputAmounts;
uint256 length;
address container;
bool hasRemainder;
}
struct PrepareFundsAfterEnterLocalVars {
uint256 length;
address container;
address[] tokens;
uint256[] amounts;
bool hasRemainder;
}
struct EmergencyExitLocalVars {
bytes32 currentStateId;
uint256 toStateNavBeforeExit;
uint256 maxSlippageCached;
uint256 expectedNavDelta;
uint256 toStateNavAfterExit;
uint256 currentStateBitmask;
uint256 toStateBitmask;
bool isExitSuccess;
}
// ---- Events ----
event Entered(uint256 navBefore, uint256 navAfter, bool hasRemainder);
event Exited(uint256 navBefore, uint256 navAfter, bytes32 stateId);
event EmergencyExited(bytes32 toStateId);
event Harvested(bytes32 stateId, uint256 navAfter);
event EmergencyExitFailed(bytes32 toStateId);
event EmergencyExitSucceeded(bytes32 toStateId);
event ReenteredToState(bytes32 stateId);
event StateUpdated(bytes32 oldStateId, bytes32 newStateId, uint256 newStateBitmask);
event NavResolutionModeUpdated(bool isNavResolutionMode);
event EmergencyModeUpdated(bool isEmergencyMode);
event InputTokenSet(address);
event OutputTokenSet(address);
event EnterMaxSlippageUpdated(uint256 oldEnterMaxSlippage, uint256 newEnterMaxSlippage);
event ExitMaxSlippageUpdated(uint256 oldExitMaxSlippage, uint256 newExitMaxSlippage);
event EmergencyExitMaxSlippageUpdated(uint256 oldEmergencyExitMaxSlippage, uint256 newEmergencyExitMaxSlippage);
// ---- Errors ----
error IncorrectStateId(bytes32 stateId);
error StateHasZeroBitmask(bytes32 stateId);
error CannotEnterStateWithLowerHeight(bytes32 toStateId, bytes32 currentStateId);
error CannotExitToStateWithHigherHeight(bytes32 toStateId, bytes32 currentStateId);
error EnterUnavailable();
error CannotExitFromNoAllocationState();
error EmergencyExitUnavailable();
error SlippageCheckFailed(uint256 navBefore, uint256 navAfter, uint256 minNavDelta);
error NavResolutionModeActivated();
error NavResolutionModeNotActivated();
error EmergencyModeActivated();
error StateNotFound(bytes32 stateId);
error NotInTargetState(bytes32 currentStateId, uint256 currentStateBitmask);
error StateAlreadyExists(bytes32 stateId);
error TargetStateAlreadySet();
error AlreadyInState(bytes32 stateId);
error TreasuryNotSet();
error TokenNotFound(address token);
error NotWhitelistedToken(address token);
error IncorrectSlippage(uint256 navDelta, uint256 maxSlippageCached);
// ---- Functions ----
/**
* @notice Returns the identifier of the current allocation state.
*/
function currentStateId() external view returns (bytes32);
/**
* @notice Returns the net asset value (NAV) of the current state in notion units.
*/
function currentStateNav() external view returns (uint256);
/**
* @notice Returns whether NAV resolution mode is active.
* @dev Used during emergency flows to lock normal enter/exit operations.
* @return True if NAV resolution mode is active, false otherwise.
*/
function isNavResolutionMode() external view returns (bool);
/**
* @notice Sets the maximum slippage allowed for enters.
* @dev Callable only by the strategy container or RESHUFFLING_EXECUTOR_ROLE.
* @param _enterMaxSlippage The maximum slippage allowed for enters in basis points.
* Must be between 0 and 1e18.
*/
function setEnterMaxSlippage(uint256 _enterMaxSlippage) external;
/**
* @notice Sets the maximum slippage allowed for exits.
* @dev Callable only by the strategy container or RESHUFFLING_EXECUTOR_ROLE.
* @param _exitMaxSlippage The maximum slippage allowed for exits in basis points.
* Must be between 0 and 1e18.
*/
function setExitMaxSlippage(uint256 _exitMaxSlippage) external;
/**
* @notice Sets the maximum slippage allowed for emergency exits.
* @dev Callable only by the strategy container or RESHUFFLING_EXECUTOR_ROLE.
* @param _emergencyExitMaxSlippage The maximum slippage allowed for emergency exits in basis points.
* Must be between 0 and 1e18.
*/
function setEmergencyExitMaxSlippage(uint256 _emergencyExitMaxSlippage) external;
/**
* @notice Enters the strategy using the provided input token amounts.
* @dev Callable only by the strategy container. Input array order must match `getInputTokens()`.
* Reverts unless NAV increases by at least `minNavDelta`.
* @param inputAmounts Amounts of input tokens provided by the container.
* @param minNavDelta Minimum required NAV increase (notion units) after enter.
* @return stateNavAfter NAV after enter (notion units).
* @return hasRemainder True if any funds remain to be prepared for the agent.
* @return remainingAmounts Amounts remaining for the agent per input token.
*/
function enter(
uint256[] memory inputAmounts,
uint256 minNavDelta
) external payable returns (uint256, bool, uint256[] memory);
/**
* @notice Exits the strategy proportionally to a share of the position.
* @dev Callable only by the strategy container. `share` is in basis points (10000 = 100%).
* Reverts if NAV drops by more than `maxNavDelta`.
* @param share Portion of the position to exit in basis points.
* @param maxNavDelta Maximum allowed NAV decrease (notion units) during exit.
* @return outputTokens Tokens transferred back to the container.
* @return outputAmounts Amounts returned per token.
*/
function exit(uint256 share, uint256 maxNavDelta) external payable returns (address[] memory, uint256[] memory);
/**
* @notice Harvests rewards, applies fees and reinvests it into the strategy.
* @dev Callable by the strategy container or HARVEST_MANAGER_ROLE.
* @return navAfter NAV after harvest (notion units).
*/
function harvest() external payable returns (uint256);
/**
* @notice Performs an emergency exit to a specific state.
* @dev Callable by the strategy container or EMERGENCY_EXECUTOR_ROLE.
* @param toStateId Destination state identifier for the emergency exit.
* @param share Portion of the position to exit in basis points (10000 = 100%).
* @param minNavDelta Minimum required NAV increase (notion units) after exit.
*/
function emergencyExit(bytes32 toStateId, uint256 share, uint256 minNavDelta) external payable;
/**
* @notice Internal function to attempt an emergency exit safely.
* @dev Can only be called by the contract itself. Used by `emergencyExit` to execute exit operations in a try-catch pattern.
* @param toStateId Destination state identifier for the emergency exit.
* @param share Portion of the position to exit in basis points (10000 = 100%).
*/
function tryEmergencyExit(bytes32 toStateId, uint256 share) external;
/**
* @notice Sets (overwrites) the list of allowed input tokens.
* @dev Callable only by the strategy container. This method overwrites the previous input tokens with the new list.
* Tokens cannot be zero addresses or duplicates.
* @param inputTokens Token addresses allowed for entering the strategy.
*/
function setInputTokens(address[] memory inputTokens) external;
/**
* @notice Sets (overwrites) the list of allowed output tokens.
* @dev Callable only by the strategy container. This method overwrites the previous output tokens with the new list.
* Tokens cannot be zero addresses or duplicates.
* @param outputTokens Token addresses expected when exiting the strategy.
*/
function setOutputTokens(address[] memory outputTokens) external;
/**
* @notice Returns the net asset value for a specific state.
* @param stateId State identifier.
*/
function stateNav(bytes32 stateId) external view returns (uint256);
/**
* @notice Returns the bitmask for a specific state.
* @param stateId State identifier.
* @return State bitmask encoding target, protocol, token flags and height.
*/
function stateBitmask(bytes32 stateId) external view returns (uint256);
/**
* @notice Returns the currently configured input tokens.
*/
function getInputTokens() external view returns (address[] memory);
/**
* @notice Returns the currently configured output tokens.
*/
function getOutputTokens() external view returns (address[] memory);
/**
* @notice Returns the registered state identifiers.
*/
function getStateIds() external view returns (bytes32[] memory);
/**
* @notice Converts a token amount into notion denomination using the oracle aggregator.
* @dev Uses the price oracle from the strategy container to get relative value.
* @param token Token address to convert.
* @param amount Token amount to convert.
* @return Notion-denominated value of the token amount.
*/
function getTokenAmountInNotion(address token, uint256 amount) external view returns (uint256);
}
contracts/interfaces/ISwapRouter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @title Interface for a universal token swap router (Exact-In model)
/// @notice Provides a unified interface for token swaps with fixed input amounts.
interface ISwapRouter {
struct PredefinedSwapParameters {
address adapter;
bytes payload;
}
struct SwapInstruction {
address adapter;
address tokenIn; // Token to swap from
address tokenOut; // Token to receive
uint256 amountIn; // Exact amount of tokenIn to swap
uint256 minAmountOut; // Minimum acceptable amount of tokenOut
bytes payload; // Arbitrary data passed to router implementation
}
event SwapAdapterWhitelisted(address indexed adapter);
event SwapAdapterBlacklisted(address indexed adapter);
event Swap(
address indexed caller,
address indexed fromToken,
address indexed toToken,
uint256 amountIn,
uint256 amountOut
);
event DefaultAdapterForTokenPairSet(address indexed tokenIn, address indexed tokenOut, address indexed adapter);
event PredefinedSwapParametersSet(
address indexed tokenIn,
address indexed tokenOut,
address indexed adapter,
bytes payload
);
event PredefinedSwapParametersUnset(address indexed tokenIn, address indexed tokenOut);
error AdapterNotWhitelisted(address adapter);
error SlippageCheckFailed(uint256 amountOutBefore, uint256 amountOutAfter, uint256 minAmountOut);
error SwapParametersNotSetForTokenPair(address tokenIn, address tokenOut);
// ---- Functions ----
/**
* @notice Preview the amount of output tokens that would be received for a given input amount.
* @dev The adapter must be whitelisted.
* @param instruction Swap instruction containing adapter, tokens, amounts, and payload.
* @return amountOut The amount of output tokens that would be received.
*/
function previewSwap(SwapInstruction memory instruction) external view returns (uint256 amountOut);
/**
* @notice Executes a token swap based on the provided instruction.
* @dev The adapter must be whitelisted. Transfers tokens from the caller and returns output tokens.
* Reverts if the actual output amount is less than `minAmountOut`.
* @param instruction Swap instruction containing adapter, tokens, amounts, and payload.
* @return amountOut Actual amount of output tokens received after the swap.
*/
function swap(SwapInstruction calldata instruction) external payable returns (uint256 amountOut);
/**
* @notice Attempts to execute a swap using predefined parameters for a token pair.
* @dev Returns false if no predefined parameters exist for the pair. Otherwise executes swap and returns true with amount.
* @param tokenIn The address of the input token.
* @param tokenOut The address of the output token.
* @param amountIn Exact amount of input tokens to swap.
* @param minAmountOut Minimum acceptable amount of output tokens.
* @return success True if predefined parameters exist and swap was executed, false otherwise.
* @return amountOut Actual amount of output tokens received (0 if success is false).
*/
function tryPredefinedSwap(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minAmountOut
) external payable returns (bool success, uint256 amountOut);
/**
* @notice Whitelists a swap adapter.
* @dev Can only be called by accounts with WHITELIST_MANAGER_ROLE.
* @param adapter The address of the swap adapter to whitelist.
*/
function whitelistSwapAdapter(address adapter) external;
/**
* @notice Blacklists a swap adapter.
* @dev Can only be called by accounts with WHITELIST_MANAGER_ROLE.
* @param adapter The address of the swap adapter to blacklist.
*/
function blacklistSwapAdapter(address adapter) external;
/**
* @notice Sets predefined swap parameters for a token pair.
* @dev Can only be called by accounts with WHITELIST_MANAGER_ROLE. The adapter must be whitelisted.
* @param tokenIn The address of the input token.
* @param tokenOut The address of the output token.
* @param adapter The address of the swap adapter to use for this pair.
* @param payload The payload to pass to the adapter during swaps.
*/
function setPredefinedSwapParameters(
address tokenIn,
address tokenOut,
address adapter,
bytes calldata payload
) external;
/**
* @notice Unsets predefined swap parameters for a token pair.
* @dev Can only be called by accounts with WHITELIST_MANAGER_ROLE.
* @param tokenIn The address of the input token.
* @param tokenOut The address of the output token.
*/
function unsetPredefinedSwapParameters(address tokenIn, address tokenOut) external;
/**
* @notice Returns the whitelist status of a swap adapter.
* @param adapter The address of the swap adapter to check.
* @return True if the adapter is whitelisted, false otherwise.
*/
function whitelistedAdapters(address adapter) external view returns (bool);
/**
* @notice Returns the predefined swap parameters for a token pair.
* @param tokenIn The address of the input token.
* @param tokenOut The address of the output token.
* @return adapter The adapter address configured for this pair.
* @return payload The payload configured for this pair.
*/
function predefinedSwapParameters(
address tokenIn,
address tokenOut
) external view returns (address adapter, bytes memory payload);
}
contracts/interfaces/IVault.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IVault {
// -- Enums --
enum VaultStatus {
Idle,
DepositBatchProcessingStarted,
DepositBatchProcessingFinished,
WithdrawBatchProcessingStarted
}
// -- Structs --
struct Limits {
uint256 maxDepositAmount;
uint256 minDepositAmount;
uint256 maxDepositBatchSize;
uint256 minDepositBatchSize;
uint256 minWithdrawBatchRatio;
}
struct RoleAddresses {
address defaultAdmin;
address containerManager;
address operator;
address configurator;
address reshufflingManager;
address reshufflingExecutor;
address emergencyPauser;
}
struct ContainerReport {
uint256 nav0;
uint256 nav1;
}
struct ClaimDepositLocalVars {
uint256 depositAmount;
uint256 batchTotalNotion;
uint256 batchNotionRemainder;
uint256 sharesToClaim;
uint256 notionToClaim;
}
struct WithdrawLocalVars {
uint256 sharesToBurn;
uint256 positionShares;
uint256 withdrawBatchIdCached;
}
struct ClaimWithdrawLocalVars {
uint256 withdrawnShares;
uint256 notionToClaim;
}
struct DepositBatchProcessingLocalVars {
uint256 totalBatchDepositAmount;
uint256 containersNumber;
uint256 batchId;
uint256 undistributedWeight;
uint256 undistributedNotionAmount;
uint256 containerAmount;
}
struct ResolveDepositBatchLocalVars {
uint256 previousBatchId;
uint256 containersNumber;
uint256 totalNav0;
uint256 totalNav1;
uint256 batchDeltaNav;
uint256 effectiveTotalSupply;
uint256 batchShares;
}
struct WithdrawBatchProcessingLocalVars {
uint256 bufferedSharesToWithdrawCached;
uint256 batchSharesPercent;
uint256 batchId;
}
// -- Events --
event MaxDepositAmountUpdated(uint256 maxDepositAmount);
event MinDepositAmountUpdated(uint256 minDepositAmount);
event MaxDepositBatchSizeUpdated(uint256 maxDepositBatchSize);
event MinDepositBatchSizeUpdated(uint256 minDepositBatchSize);
event MinWithdrawBatchRatioUpdated(uint256 minWithdrawBatchRatio);
event ForcedDepositThresholdUpdated(uint256 previousForcedDepositThreshold, uint256 newForcedDepositThreshold);
event ForcedWithdrawThresholdUpdated(uint256 previousForcedWithdrawThreshold, uint256 newForcedWithdrawThreshold);
event ForcedBatchBlockLimitUpdated(uint256 previousForcedBatchBlockLimit, uint256 newForcedBatchBlockLimit);
event ContainerAdded(address container);
event ContainerRemoved(address container);
event ContainerWeightsUpdated(address[] containers, uint256[] weights);
event Deposit(address indexed user, address indexed onBehalfOf, uint256 indexed batchId, uint256 amount);
event DepositClaimed(
address indexed user,
address indexed onBehalfOf,
uint256 indexed batchId,
uint256 sharesClaimed,
uint256 notionClaimed
);
event Withdraw(address indexed user, uint256 indexed batchId, uint256 amountShares);
event WithdrawClaimed(address indexed user, address indexed onBehalfOf, uint256 indexed batchId, uint256 amount);
event DepositBatchProcessingStarted(uint256 batchId, uint256 batchAmount);
event DepositBatchSkipped(uint256 batchId, uint256 batchAmount);
event DepositReportReceived(
address indexed container,
uint256 indexed batchId,
uint256 nav0,
uint256 nav1,
uint256 notionRemainder
);
event DepositBatchProcessingFinished(
uint256 batchId,
uint256 batchShares,
uint256 batchDeltaNav,
uint256 totalNav1
);
event WithdrawBatchProcessingStarted(uint256 batchId, uint256 batchShares, uint256 batchSharesPercent);
event WithdrawBatchSkipped(uint256 batchId, uint256 batchAmount);
event WithdrawReportReceived(address indexed container, uint256 indexed batchId, uint256 notionAmount);
event WithdrawBatchProcessingFinished(uint256 batchId, uint256 withdrawnNotionAmount);
event ReshufflingGatewayUpdated(address indexed previousGateway, address indexed newGateway);
event ReshufflingModeEnabled();
event ReshufflingModeDisabled();
// ---- Errors ----
// Access Control
error NotContainer();
// State
error ContainerAlreadyExists();
error ContainerNotFound(address container);
error DuplicatingContainer(address container);
error ContainerAlreadyReported(address container);
error NoContainers();
error NotEnoughNotion();
error NotEnoughSharesWithdrawn(uint256 batchSharesPercent);
// Input Validation
error NothingToWithdraw();
error IncorrectBatchId();
error IncorrectReport();
error IncorrectVaultStatus(VaultStatus status);
error IncorrectWeights(uint256 weightsSum);
error WeightRoundsToZero(address container, uint256 weight);
error ContainerForChainIdAlreadyExists(uint256 chainId, address container);
error IncorrectContainerType();
error IncorrectMaxDepositAmount();
error IncorrectMinDepositAmount();
error IncorrectMaxDepositBatchSize();
error IncorrectMinDepositBatchSize();
error IncorrectMinWithdrawBatchRatio();
error IncorrectForcedDepositThreshold();
error IncorrectForcedWithdrawThreshold();
error IncorrectForcedBatchBlockLimit();
// Business Logic
error DepositBatchCapReached();
error DepositBatchSizeTooSmall();
error CannotSkipBatch();
error CannotSkipBatchInEmptyVault();
error CannotSkipForcedBatch();
error IncorrectNotionDistribution();
error MaxContainersReached();
error MissingContainerReport();
error ZeroContainerWeight(address container);
error IncorrectContainerAmount(address container);
// ---- Functions ----
/**
* @notice Sets the reshuffling gateway address.
* @dev Can only be called by accounts with RESHUFFLING_MANAGER_ROLE.
* @param _reshufflingGateway The address of the reshuffling gateway contract
*/
function setReshufflingGateway(address _reshufflingGateway) external;
/**
* @notice Enables the reshuffling mode.
* @dev Can only be called by accounts with RESHUFFLING_MANAGER_ROLE. Requires reshuffling gateway to be set.
*/
function enableReshufflingMode() external;
/**
* @notice Disables the reshuffling mode.
* @dev Can only be called by accounts with RESHUFFLING_EXECUTOR_ROLE. Requires reshuffling mode to be enabled.
* All containers must have a weight greater than 0 to disable reshuffling mode
*/
function disableReshufflingMode() external;
/**
* @notice Sets the maximum deposit amount per transaction.
* @dev Can only be called by accounts with CONFIGURATOR_ROLE.
* @param _maxDepositAmount The maximum amount that can be deposited in a single transaction
*/
function setMaxDepositAmount(uint256 _maxDepositAmount) external;
/**
* @notice Sets the minimum deposit amount.
* @dev Can only be called by accounts with CONFIGURATOR_ROLE.
* @param _minDepositAmount The minimum amount required for a deposit transaction
*/
function setMinDepositAmount(uint256 _minDepositAmount) external;
/**
* @notice Sets the maximum deposit batch size.
* @dev Can only be called by accounts with CONFIGURATOR_ROLE.
* @param _maxDepositBatchSize The maximum total amount that can be accumulated in a deposit batch
*/
function setMaxDepositBatchSize(uint256 _maxDepositBatchSize) external;
/**
* @notice Sets the minimum deposit batch size.
* @dev Can only be called by accounts with CONFIGURATOR_ROLE.
* @param _minDepositBatchSize The minimum total amount required to start processing a deposit batch
*/
function setMinDepositBatchSize(uint256 _minDepositBatchSize) external;
/**
* @notice Sets the forced deposit threshold notion amount.
* @dev Can only be called by accounts with CONFIGURATOR_ROLE.
* @param _forcedDepositThreshold The threshold notion amount for forced deposit batch processing
*/
function setForcedDepositThreshold(uint256 _forcedDepositThreshold) external;
/**
* @notice Sets the forced withdraw threshold shares amount.
* @dev Can only be called by accounts with CONFIGURATOR_ROLE.
* @param _forcedWithdrawThreshold The threshold shares amount for forced withdraw batch processing
*/
function setForcedWithdrawThreshold(uint256 _forcedWithdrawThreshold) external;
/**
* @notice Sets the forced batch block limit.
* @dev Can only be called by accounts with CONFIGURATOR_ROLE.
* @param _forcedBatchBlockLimit The number of blocks after which a forced batch must be processed
*/
function setForcedBatchBlockLimit(uint256 _forcedBatchBlockLimit) external;
/**
* @notice Sets the minimum withdraw batch ratio.
* @dev Can only be called by accounts with CONFIGURATOR_ROLE. Ratio is in basis points (10000 = 100%).
* @param _minWithdrawBatchRatio The minimum percentage of total shares that must be withdrawn to start processing a withdraw batch
*/
function setMinWithdrawBatchRatio(uint256 _minWithdrawBatchRatio) external;
/**
* @notice Returns all registered containers and their weights.
* @return containers Array of container addresses
* @return weights Array of corresponding weights in basis points
*/
function getContainers() external view returns (address[] memory containers, uint256[] memory weights);
/**
* @notice Adds a new container to the vault.
* @dev Can only be called by accounts with CONTAINER_MANAGER_ROLE. If this is the first container, it automatically gets 100% weight.
* @param container The address of the container contract to add
* @param chainId The chain ID of the container
*/
function addContainer(address container, uint256 chainId) external;
/**
* @notice Sets the weights for multiple containers.
* @dev Can only be called by accounts with CONTAINER_MANAGER_ROLE. Requires vault status to be Idle. Setting weight to 0 removes the container.
* @param containers Array of container addresses to update weights for
* @param weights Array of corresponding weights in basis points (10000 = 100%)
*/
function setContainerWeights(address[] calldata containers, uint256[] calldata weights) external;
/**
* @notice Checks if an address is a registered container.
* @param container The address to check
* @return True if the address is a registered container, false otherwise
*/
function isContainer(address container) external view returns (bool);
/**
* @notice Deposits notion tokens into the vault.
* @dev Deposits are buffered and processed in batches. The amount must be between minDepositAmount and maxDepositAmount.
* @param amount The amount of notion tokens to deposit
* @param onBehalfOf The address that will receive the vault shares
*/
function deposit(uint256 amount, address onBehalfOf) external;
/**
* @notice Deposits notion tokens into the vault using ERC20 permit.
* @dev Allows depositing without a prior approval transaction by using ERC20 permit signature.
* @param amount The amount of notion tokens to deposit
* @param onBehalfOf The address that will receive the vault shares
* @param deadline The deadline for the permit signature
* @param v The recovery id of the permit signature
* @param r The r component of the permit signature
* @param s The s component of the permit signature
*/
function depositWithPermit(
uint256 amount,
address onBehalfOf,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @notice Claims vault shares and notion remainder for a completed deposit batch.
* @dev Can only be called after the deposit batch has been resolved. Calculates shares based on the batch's NAV change.
* @param batchId The ID of the deposit batch to claim from
* @param onBehalfOf The address that will receive the shares and notion remainder
* @return sharesClaimed The amount of vault shares claimed
* @return notionClaimed The amount of notion tokens claimed
*/
function claimDeposit(
uint256 batchId,
address onBehalfOf
) external returns (uint256 sharesClaimed, uint256 notionClaimed);
/**
* @notice Initiates a withdrawal by burning a percentage of the caller's vault shares.
* @dev The shares are transferred to the vault and buffered for batch processing. The percentage is in basis points (10000 = 100%).
* @param sharesPercent The percentage of caller's shares to withdraw, in basis points
*/
function withdraw(uint256 sharesPercent) external;
/**
* @notice Claims notion tokens for a completed withdrawal batch.
* @dev Can only be called after the withdrawal batch has been resolved. Burns the shares and transfers notion tokens.
* @param batchId The ID of the withdrawal batch to claim from
* @param onBehalfOf The address that will receive the notion tokens
* @return notionClaimed The amount of notion tokens claimed
*/
function claimWithdraw(uint256 batchId, address onBehalfOf) external returns (uint256 notionClaimed);
/**
* @notice Checks if all containers have submitted their deposit reports.
* @return True if all containers have reported, false otherwise
*/
function isDepositReportComplete() external view returns (bool);
/**
* @notice Starts processing a new deposit batch.
* @dev Can only be called by accounts with OPERATOR_ROLE. Requires vault status to be Idle and buffered deposits to meet minimum batch size. Distributes deposits to containers based on their weights.
*/
function startDepositBatchProcessing() external;
/**
* @notice Skips processing the current deposit batch if it's too small.
* @dev Can only be called by accounts with OPERATOR_ROLE. Requires vault status to be Idle and buffered deposits to be below minimum batch size.
*/
function skipDepositBatch() external;
/**
* @notice Reports deposit results from a container.
* @dev Can only be called by registered containers. Each container can only report once per batch. Requires nav1 >= nav0.
* @param report The container report containing NAV values before and after the deposit
* @param notionRemainder Any notion tokens that couldn't be deposited and should be returned to users
*/
function reportDeposit(ContainerReport calldata report, uint256 notionRemainder) external;
/**
* @notice Resolves a deposit batch after all containers have reported.
* @dev Can only be called by accounts with OPERATOR_ROLE. Calculates total NAV change and mints corresponding vault shares.
*/
function resolveDepositBatch() external;
/**
* @notice Checks if all containers have submitted their withdrawal reports.
* @return True if all containers have reported, false otherwise
*/
function isWithdrawReportComplete() external view returns (bool);
/**
* @notice Starts processing a new withdrawal batch.
* @dev Can only be called by accounts with OPERATOR_ROLE. Requires vault status to be DepositBatchProcessingFinished and buffered shares to meet minimum batch ratio.
*/
function startWithdrawBatchProcessing() external;
/**
* @notice Skips processing the current withdrawal batch if it's too small.
* @dev Can only be called by accounts with OPERATOR_ROLE. Requires vault status to be DepositBatchProcessingFinished and buffered shares to be below minimum batch ratio.
*/
function skipWithdrawBatch() external;
/**
* @notice Reports withdrawal results from a container.
* @dev Can only be called by registered containers. Each container can only report once per batch. Transfers notion tokens from the container to the vault.
* @param notionAmount The amount of notion tokens the container is returning for the withdrawal
*/
function reportWithdraw(uint256 notionAmount) external;
/**
* @notice Resolves a withdrawal batch after all containers have reported.
* @dev Can only be called by accounts with OPERATOR_ROLE. Sets vault status back to Idle, making it ready for the next deposit batch.
*/
function resolveWithdrawBatch() external;
/**
* @notice Pauses all state-changing operations in the vault.
* @dev Can only be called by accounts with EMERGENCY_PAUSER_ROLE.
*/
function pause() external;
/**
* @notice Unpauses the vault and re-enables state-changing operations.
* @dev Can only be called by accounts with EMERGENCY_PAUSER_ROLE.
*/
function unpause() external;
/**
* @notice Returns the current vault status.
* @return The current status of the vault (Idle, DepositBatchProcessingStarted, DepositBatchProcessingFinished, or WithdrawBatchProcessingStarted)
*/
function status() external view returns (VaultStatus);
/**
* @notice Returns the maximum deposit amount per transaction.
* @return The maximum amount that can be deposited in a single transaction
*/
function maxDepositAmount() external view returns (uint256);
/**
* @notice Returns the minimum deposit amount.
* @return The minimum amount required for a deposit transaction
*/
function minDepositAmount() external view returns (uint256);
/**
* @notice Returns the maximum deposit batch size.
* @return The maximum total amount that can be accumulated in a deposit batch
*/
function maxDepositBatchSize() external view returns (uint256);
/**
* @notice Returns the minimum deposit batch size.
* @return The minimum total amount required to start processing a deposit batch
*/
function minDepositBatchSize() external view returns (uint256);
/**
* @notice Returns the minimum withdraw batch ratio.
* @return The minimum percentage of total shares that must be withdrawn to start processing a withdraw batch, in basis points
*/
function minWithdrawBatchRatio() external view returns (uint256);
/**
* @notice Returns the notion token contract address.
* @return The IERC20 token contract representing the notion token
*/
function notion() external view returns (IERC20);
/**
* @notice Returns the current deposit batch ID.
* @return The ID of the current deposit batch being processed
*/
function depositBatchId() external view returns (uint256);
/**
* @notice Returns the last resolved deposit batch ID.
* @return The ID of the most recently resolved deposit batch
*/
function lastResolvedDepositBatchId() external view returns (uint256);
/**
* @notice Returns the total amount of buffered deposits waiting to be processed.
* @return The total amount of notion tokens currently buffered for the next deposit batch
*/
function bufferedDeposits() external view returns (uint256);
/**
* @notice Returns the pending deposit amount for a specific user in a specific batch.
* @param batchId The ID of the deposit batch
* @param user The address of the user
* @return The amount of notion tokens pending for the user in the specified batch
*/
function pendingBatchDeposits(uint256 batchId, address user) external view returns (uint256);
/**
* @notice Returns the total notion amount for a specific deposit batch.
* @param batchId The ID of the deposit batch
* @return The total amount of notion tokens in the specified deposit batch
*/
function depositBatchTotalNotion(uint256 batchId) external view returns (uint256);
/**
* @notice Returns the total shares minted for a specific deposit batch.
* @param batchId The ID of the deposit batch
* @return The total amount of vault shares minted for the specified deposit batch
*/
function depositBatchTotalShares(uint256 batchId) external view returns (uint256);
/**
* @notice Returns the notion remainder for a specific deposit batch.
* @param batchId The ID of the deposit batch
* @return The amount of notion tokens that couldn't be deposited and should be returned to users
*/
function batchNotionRemainder(uint256 batchId) external view returns (uint256);
/**
* @notice Returns the total unclaimed notion remainder across all batches.
* @return The total amount of notion remainder that has not yet been claimed by users
*/
function totalUnclaimedNotionRemainder() external view returns (uint256);
/**
* @notice Returns the current withdraw batch ID.
* @return The ID of the current withdraw batch being processed
*/
function withdrawBatchId() external view returns (uint256);
/**
* @notice Returns the last resolved withdraw batch ID.
* @return The ID of the most recently resolved withdraw batch
*/
function lastResolvedWithdrawBatchId() external view returns (uint256);
/**
* @notice Returns the total amount of buffered shares waiting to be withdrawn.
* @return The total amount of vault shares currently buffered for the next withdraw batch
*/
function bufferedSharesToWithdraw() external view returns (uint256);
/**
* @notice Returns the pending withdrawal amount for a specific user in a specific batch.
* @param batchId The ID of the withdraw batch
* @param user The address of the user
* @return The amount of vault shares pending for withdrawal by the user in the specified batch
*/
function pendingBatchWithdrawals(uint256 batchId, address user) external view returns (uint256);
/**
* @notice Returns the total shares for a specific withdraw batch.
* @param batchId The ID of the withdraw batch
* @return The total amount of vault shares in the specified withdraw batch
*/
function withdrawBatchTotalShares(uint256 batchId) external view returns (uint256);
/**
* @notice Returns the total notion amount for a specific withdraw batch.
* @param batchId The ID of the withdraw batch
* @return The total amount of notion tokens available for withdrawal in the specified batch
*/
function withdrawBatchTotalNotion(uint256 batchId) external view returns (uint256);
/**
* @notice Returns the total unclaimed notion for withdrawals across all batches.
* @return The total amount of notion tokens available for withdrawal that have not yet been claimed by users
*/
function totalUnclaimedNotionForWithdraw() external view returns (uint256);
/**
* @notice Returns the weight of a specific container.
* @param container The address of the container
* @return The weight of the container in basis points (10000 = 100%)
*/
function containerWeights(address container) external view returns (uint256);
/**
* @notice Returns the container address for a specific chain ID.
* @param chainId The chain ID
* @return The address of the container, or zero address if container for that chain ID is not set
*/
function containerByChainId(uint256 chainId) external view returns (address);
/**
* @notice Returns the reshuffling gateway address.
* @return The address of the reshuffling gateway contract, or zero address if not set
*/
function reshufflingGateway() external view returns (address);
/**
* @notice Returns whether the vault is in reshuffling mode.
* @return True if the vault is in reshuffling mode, false otherwise
*/
function isReshuffling() external view returns (bool);
/**
* @notice Returns the forced deposit threshold notion amount.
* @return The threshold notion amount for forced deposit batch processing
*/
function forcedDepositThreshold() external view returns (uint256);
/**
* @notice Returns the forced withdraw threshold shares amount.
* @return The threshold shares amount for forced withdraw batch processing
*/
function forcedWithdrawThreshold() external view returns (uint256);
/**
* @notice Returns the forced batch block limit.
* @return The number of blocks after which a forced batch must be processed
*/
function forcedBatchBlockLimit() external view returns (uint256);
/**
* @notice Returns the pending burn shares.
* @return The amount of vault shares that are pending to be burned
*/
function pendingBurnShares() external view returns (uint256);
}
contracts/libraries/EnumerableAddressSetExtended.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
/// @title EnumerableAddressSetExtended
/// @notice Helper to fetch index of an address inside EnumerableSet.
library EnumerableAddressSetExtended {
using EnumerableSet for EnumerableSet.AddressSet;
/**
* @notice Returns whether a value exists in the set and its index.
* @dev Index is zero-based when found. If not found, returns (false, 0).
* @param set Storage set reference.
* @param value Address to look up.
* @return found True if present.
* @return index Zero-based index when found; undefined if not found.
*/
function indexOf(
EnumerableSet.AddressSet storage set,
address value
) internal view returns (bool found, uint256 index) {
uint256 i = set._inner._positions[bytes32(uint256(uint160(value)))];
if (i == 0) return (false, 0);
return (true, i - 1);
}
}
contracts/libraries/Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
library Errors {
// -- Access Control Errors --
error Unauthorized();
// -- State Errors --
error AlreadyBlacklisted();
error AlreadyWhitelisted();
error NotImplemented();
error TokenAlreadySet(address value);
error AlreadySet();
// -- Input Validation Errors --
error ArrayLengthMismatch();
error InvalidArrayLength();
error IncorrectAmount();
error IncorrectContainerStatus();
error ZeroAddress();
error ZeroAmount();
error ZeroArrayLength();
error IncorrectContainerType(address container, uint8 expected, uint8 received);
error DuplicatingAddressInArray(address entry);
error IncorrectChainId(uint256 chainId);
error SettingSameBooleanValue();
error SettingSameValue();
// -- Business Logic Errors --
error ReshufflingModeEnabled();
error ReshufflingModeDisabled();
error ReshufflingGatewayNotSet();
error NotEnoughNativeToken(uint256 value, uint256 balance);
error NotEnoughTokens(address token, uint256 amount, uint256 balance);
error SwapFailed(address tokenIn, address tokenOut, uint256 amountIn, uint256 minAmountOut);
}
lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
struct AccessControlStorage {
mapping(bytes32 role => RoleData) _roles;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;
function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
assembly {
$.slot := AccessControlStorageLocation
}
}
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
AccessControlStorage storage $ = _getAccessControlStorage();
bytes32 previousAdminRole = getRoleAdmin(role);
$._roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (!hasRole(role, account)) {
$._roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (hasRole(role, account)) {
$._roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Pausable
struct PausableStorage {
bool _paused;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;
function _getPausableStorage() private pure returns (PausableStorage storage $) {
assembly {
$.slot := PausableStorageLocation
}
}
/**
* @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 Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
}
/**
* @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) {
PausableStorage storage $ = _getPausableStorage();
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 {
PausableStorage storage $ = _getPausableStorage();
$._paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
emit Unpaused(_msgSender());
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// On the first call to nonReentrant, _status will be NOT_ENTERED
if ($._status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
$._status = ENTERED;
}
function _nonReentrantAfter() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
$._status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165Upgradeable is Initializable, IERC165 {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
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);
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.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 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);
}
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 5,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:forge-std/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/src/",
"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"lib/openzeppelin-contracts-upgradeable/:erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"lib/openzeppelin-contracts-upgradeable/:forge-std/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/src/",
"lib/openzeppelin-contracts-upgradeable/:halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"lib/openzeppelin-foundry-upgrades/:forge-std/=lib/openzeppelin-foundry-upgrades/lib/forge-std/src/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
"openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.