Skip to content
Verified contractExactBUSL-1.1

ClearFactory

Address0x78aba0729345219b8ec4d5c9c19d23186e0803fb
Balance

0 ETH

 

Transactions

2,257

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
24,477,332
Creation transaction
0x5a412d7646…dbd2397625

project/contracts/vault/ClearFactory.sol

// SPDX-License-Identifier: BUSL-1.1

//████████╗██████╗ ███████╗██╗   ██╗███████╗███████╗
//╚══██╔══╝██╔══██╗██╔════╝██║   ██║██╔════╝██╔════╝
//   ██║   ██████╔╝█████╗  ██║   ██║█████╗  █████╗
//   ██║   ██╔══██╗██╔══╝  ╚██╗ ██╔╝██╔══╝  ██╔══╝
//   ██║   ██║  ██║███████╗ ╚████╔╝ ███████╗███████╗
//   ╚═╝   ╚═╝  ╚═╝╚══════╝  ╚═══╝  ╚══════╝╚══════╝

pragma solidity ^0.8.24;

import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {AccessManaged} from "@openzeppelin/contracts/access/manager/AccessManaged.sol";

import {IClearIOU} from "../interfaces/IClearIOU.sol";
import {IClearVault} from "../interfaces/IClearVault.sol";
import {IClearFactory} from "../interfaces/IClearFactory.sol";
import {ICurveStableSwapFactory} from "../interfaces/external/ICurveStableSwapFactory.sol";

/**
 * @title ClearFactory
 * @notice Factory contract for deploying and managing Clear protocol vault instances
 * @dev Manages deployment of ClearVault and ClearIOU contracts, integrates with Curve pools,
 *      and provides administrative functions for vault configuration and upgrades.
 *      Implements access control to restrict factory operations to authorized roles.
 * @author Clear Protocol Team
 */
contract ClearFactory is IClearFactory, AccessManaged {

    /**
     * @notice The current version of the vault logic contract
     */
    uint256 public VAULT_VERSION;

    /**
     * @notice The current version of the iou logic contract
     */
    uint256 public IOU_VERSION;

    /**
     * @notice The address of the treasury
     */
    address public treasury;

    /**
     * @notice The implementation address of the vault
     */
    address public vaultImplementation;

    /**
     * @notice The implementation address of the iou
     */
    address public iouImplementation;

    /**
     * @notice The curve factory address
     */
    address public curveFactory;

    /**
     * @notice The total number of vaults created by the factory
     */
    uint256 public vaultsLength;

    /**
     * @notice Mapping from vault index to vault address
     */
    mapping(uint256 => address) public vaults;


    /// @notice Mapping indicating whether an address is a vault deployed by this factory
    mapping(address => bool) public isVault;

    /// @notice Mapping of addresses authorized as rebalance swap targets
    /// @dev Only targets explicitly allowed here can be passed to rebalance()
    mapping(address => bool) public allowedRebalanceTarget;


    /**
     * @notice Initializes the ClearFactory with required addresses and initial configuration
     * @dev Sets up the factory with authority, treasury, implementation addresses, and curve factory
     * @param _authority The address of the access control authority contract
     * @param _treasury The address where protocol fees will be collected
     * @param _vaultImplementation The implementation address for vault proxy deployments
     * @param _iouImplementation The implementation address for IOU token proxy deployments
     * @param _curveFactory The address of the Curve factory for creating liquidity pools
     */
    constructor(
        address _authority,
        address _treasury,
        address _vaultImplementation,
        address _iouImplementation,
        address _curveFactory
    ) AccessManaged(_authority) {
        treasury = _treasury;
        VAULT_VERSION = 1;
        IOU_VERSION = 1;
        vaultImplementation = _vaultImplementation;
        iouImplementation = _iouImplementation;
        curveFactory = _curveFactory;
        
        emit NewVaultImplementation(VAULT_VERSION, _vaultImplementation);
        emit NewIOUImplementation(IOU_VERSION, _iouImplementation);
    }

    /// @notice Restricts function access to vaults deployed by this factory
    /// @dev Reverts with InvalidVaultAddress if the address is not a registered vault
    /// @param _address The address to validate as a factory-deployed vault
    modifier onlyValidVault(address _address) {
        if(!isVault[_address]) revert InvalidVaultAddress(_address);
        _;
    }

    /**
     * @notice Deploys a new ClearVault contract instance
     * @dev Creates a minimal proxy clone of the vault implementation and initializes it
     *      Only callable by addresses with restricted access
     * @param _name The name for the new vault token
     * @param _symbol The symbol for the new vault token
     * @custom:emits NewClearVault
     */
    function deployNewVault(
        string memory _name,
        string memory _symbol,
        string memory _plainPoolName,
        string memory _plainPoolSymbol,
        address[] memory _tokens
    ) external restricted {
        uint256 length = _tokens.length;
        address plainpool = ICurveStableSwapFactory(curveFactory).deploy_plain_pool(
            _plainPoolName,
            _plainPoolSymbol,
            _tokens,
            1000, // A
            1000000, // fee
            100000000000, //offpeg_fee_multiplier
            866, //ma_exp_time
            0, //implementation_idx
            new uint8[](length),
            new bytes4[](length),
            new address[](length)
        );

        address vaultProxy = Clones.clone(vaultImplementation);
        uint256 vLength = vaultsLength;

        emit NewClearVault(
            vLength,
            vaultImplementation,
            vaultProxy,
            _name,
            _symbol,
            _tokens,
            plainpool
        );

        IClearVault(vaultProxy).initialize(
            authority(),
            _name,
            _symbol,
            plainpool,
            _tokens
        );

        isVault[vaultProxy] = true;
        vaults[vaultsLength] = address(vaultProxy);
        vaultsLength += 1;
    }

    /**
     * @notice Initializes a token in an existing vault by deploying its IOU token and Curve meta pool
     * @dev Deploys a ClearIOU proxy via minimal clone, creates a Curve meta pool pairing the IOU
     *      against the vault's plain pool, then calls vault.initializeToken().
     *      Only callable by addresses with restricted access on a valid factory vault.
     * @param _vault The vault address to initialize the token in
     * @param _token The underlying ERC20 token address to configure
     * @param _adapter The ERC4626 yield adapter address for the token
     * @param _desiredExposureBps Desired token exposure in basis points (10000 = 100%)
     * @param _maxExposureBps Maximum allowed token exposure in basis points (10000 = 100%)
     * @param _iouName The name of the IOU ERC20 token to deploy
     * @param _iouSymbol The symbol of the IOU ERC20 token to deploy
     * @param _metaPoolName The name for the Curve IOU meta pool
     * @param _metaPoolSymbol The symbol for the Curve IOU meta pool
     */
    function initializeToken(
        address _vault,
        address _token,
        address _adapter,
        uint256 _desiredExposureBps,
        uint256 _maxExposureBps,
        string memory _iouName,
        string memory _iouSymbol,
        string memory _metaPoolName,
        string memory _metaPoolSymbol
    ) external onlyValidVault(_vault) restricted {

        address iouProxy = _deployIou(
            _vault,
            _token,
            _iouName,
            _iouSymbol
        );

        address metapool = ICurveStableSwapFactory(curveFactory).deploy_metapool(
             IClearVault(_vault).tokensCurvePool(),
            _metaPoolName,
            _metaPoolSymbol,
            iouProxy,
            1000, // A
            1000000, // fee
            100000000000, //offpeg_fee_multiplier
            866, //ma_exp_time
            0, //implementation_idx
            uint8(0),
            bytes4(0),
            address(0)
        );

        IClearVault(_vault).initializeToken(
            _token, 
            iouProxy, 
            metapool, 
            _adapter,
            _desiredExposureBps,
            _maxExposureBps
        );
    }

    /**
     * @notice Deploys a new ClearIOU proxy and initializes it for a vault/token pair
     * @dev Creates a minimal clone of the IOU implementation and calls initialize on it
     * @param _vault The vault that will manage the new IOU token
     * @param _token The underlying token the IOU represents
     * @param _name The name of the IOU ERC20 token
     * @param _symbol The symbol of the IOU ERC20 token
     * @return The address of the newly deployed IOU proxy
     */
    function _deployIou(
        address _vault,
        address _token,
        string memory _name,
        string memory _symbol
    ) internal returns (address) {
        address iouProxy = Clones.clone(iouImplementation);
        IClearIOU(iouProxy).initialize(
            authority(),
            _vault,
            treasury,
            _token,
            _name,
            _symbol
        );

        return iouProxy;
    }

    /**
     * @notice Packs two token addresses into a dynamic array for Curve pool deployment
     * @param _coin0 The first token address
     * @param _coin1 The second token address
     * @return A two-element address array [_coin0, _coin1]
     */
    function _formatCoins(
        address _coin0,
        address _coin1
    ) internal pure returns (address[] memory) {
        address[] memory coins = new address[](2);
        coins[0] = _coin0;
        coins[1] = _coin1;
        return coins;
    }

    /**
     * @notice Changes the yield adapter for a specific token in a vault
     * @dev Updates the adapter used for yield generation on the specified token
     *      Only callable by addresses with restricted access
     * @param _vault The address of the vault
     * @param _token The address of the token
     * @param _newAdapter The address of the new adapter contract
     */
    function changeAdapter(
        address _vault, 
        address _token, 
        address _newAdapter
    ) external onlyValidVault(_vault) restricted {
        IClearVault(_vault).changeAdapter( 
            _token, 
            _newAdapter
        );
    }

    /**
     * @notice Updates the maximum exposure limit for a token in a vault
     * @dev Changes the maximum percentage of vault assets that can be allocated to this token
     *      Only callable by addresses with restricted access
     * @param _vault The address of the vault
     * @param _token The address of the token
     * @param _newDesiredExposureBps The new desired exposure in basis points (10000 = 100%)
     * @param _newMaximalExposureBps The new maximum exposure in basis points (10000 = 100%)
     */
    function setTokenExposureConfiguration(
        address _vault, 
        address _token, 
        uint256 _newDesiredExposureBps,
        uint256 _newMaximalExposureBps
    ) external onlyValidVault(_vault) restricted {        
        IClearVault(_vault).setTokenExposureConfiguration( 
           _token,
           _newDesiredExposureBps,
           _newMaximalExposureBps
        );
    }

    /**
     * @notice Updates the maximum allowed spread for rebalancing operations
     * @dev Sets the maximum slippage tolerance for rebalancing swaps in basis points
     *      Only callable by addresses with restricted access
     * @param _vault The address of the vault
     * @param _newMaximalExposureBps The new maximum rebalance spread in basis points
     */
    function setMaximumRebalanceBpsSpread(
        address _vault, 
        uint256 _newMaximalExposureBps
    ) external onlyValidVault(_vault) restricted {
        IClearVault(_vault).setMaximumRebalanceBpsSpread( 
           _newMaximalExposureBps
        );
    }

    /**
     * @notice Updates the maximum deviation allowed from desired token exposures for a vault
     * @dev Sets the tolerance range for token exposure deviations before rebalancing is required
     * @param _vault The address of the vault to update
     * @param _newDesiredExposureMaximalBpsSpread The new maximum deviation in basis points (10000 = 100%)
     */
    function setDesiredExposureMaximalBpsSpread(
        address _vault, 
        uint256 _newDesiredExposureMaximalBpsSpread
    ) external onlyValidVault(_vault) restricted {
        IClearVault(_vault).setDesiredExposureMaximalBpsSpread( 
           _newDesiredExposureMaximalBpsSpread
        );
    }

    /**
     * @notice Updates the IOU minting fee for a vault
     * @dev Changes the fee charged when minting IOU tokens during swaps
     *      Only callable by addresses with restricted access
     * @param _vault The address of the vault
     * @param _newLpFeeBps The new LP fee in basis points (10000 = 100%)
     * @param _newTreasuryFeeBps The new treasury fee in basis points (10000 = 100%)
     */
    function setIouFeeBps(
        address _vault, 
        uint256 _newLpFeeBps,
        uint256 _newTreasuryFeeBps
    ) external onlyValidVault(_vault) restricted {
        IClearVault(_vault).setIouFeeBps( 
           _newLpFeeBps,
           _newTreasuryFeeBps
        );
    }

    /**
     * @notice Executes a rebalancing operation between two tokens in a vault
     * @dev Performs a swap to rebalance vault exposure using external liquidity sources
     *      Only callable by addresses with restricted access
     * @param _vault The address of the vault
     * @param _from The token to sell
     * @param _to The token to buy
     * @param _approval The contract address to approve for token spending
     * @param _target The contract address to call for the swap
     * @param _amount The amount of tokens to swap
     * @param _payload The encoded call data for the swap
     */
    function rebalance(
        address _vault,
        address _from,
        address _to,
        address _approval, 
        address _target, 
        uint256 _amount, 
        bytes calldata _payload
    ) external onlyValidVault(_vault) restricted {
        if(!allowedRebalanceTarget[_target]) revert UnauthorizedRebalanceTarget();
        IClearVault(_vault).rebalance(
            _from, 
            _to, 
            _approval, 
            _target, 
            _amount, 
            _payload
        );
    }

    /**
     * @notice Grants or revokes authorization for a rebalance swap target
     * @dev Updates the allowedRebalanceTarget mapping; only authorized targets can be used in rebalance()
     * @param _allowed Whether the target should be authorized (true) or revoked (false)
     * @param _target The contract address to authorize or revoke as a rebalance target
     */
    function setRebalanceTarget(bool _allowed, address _target) external restricted {
        allowedRebalanceTarget[_target] = _allowed;
    }

    /**
     * @notice Upgrades the vault implementation to a new version
     * @dev Updates the implementation address for future vault deployments and increments version
     *      Only callable by addresses with restricted access
     * @param _implementation The address of the new vault implementation contract
     * @custom:emits NewVaultImplementation
     */
    function upgradeVault(address _implementation) external restricted {
        VAULT_VERSION += 1;
        vaultImplementation = _implementation;
        emit NewVaultImplementation(VAULT_VERSION, _implementation);
    }

    /**
     * @notice Upgrades the IOU token implementation to a new version
     * @dev Updates the implementation address for future IOU deployments and increments version
     *      Only callable by addresses with restricted access
     * @param _implementation The address of the new IOU implementation contract
     * @custom:emits NewIOUImplementation
     */
    function upgradeIOU(address _implementation) external restricted {
        IOU_VERSION += 1;
        iouImplementation = _implementation;
        emit NewIOUImplementation(IOU_VERSION, _implementation);
    }

    /**
     * @notice Retrieves vault addresses for multiple vault indices in a single call
     * @dev Efficiently returns an array of vault addresses for the provided indices
     * @param _indexes The array of vault indices to query
     * @return An array of vault addresses corresponding to the given indices
     */
    function getBatchVaultAddresses(
        uint256[] memory _indexes
    ) external view returns (address[] memory) {
        address[] memory vaultAddresses = new address[](_indexes.length);
        for (uint256 i = 0; i < _indexes.length;) {
            vaultAddresses[i] = vaults[_indexes[i]];
            unchecked { ++i; }
        }

        return vaultAddresses;
    }
}

npm/@openzeppelin/[email protected]/access/manager/AccessManaged.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/manager/AccessManaged.sol)

pragma solidity ^0.8.20;

import {AuthorityUtils} from "./AuthorityUtils.sol";
import {IAccessManager} from "./IAccessManager.sol";
import {IAccessManaged} from "./IAccessManaged.sol";
import {Context} from "../../utils/Context.sol";

/**
 * @dev This contract module makes available a {restricted} modifier. Functions decorated with this modifier will be
 * permissioned according to an "authority": a contract like {AccessManager} that follows the {IAuthority} interface,
 * implementing a policy that allows certain callers to access certain functions.
 *
 * IMPORTANT: The `restricted` modifier should never be used on `internal` functions, judiciously used in `public`
 * functions, and ideally only used in `external` functions. See {restricted}.
 */
abstract contract AccessManaged is Context, IAccessManaged {
    address private _authority;

    bool private _consumingSchedule;

    /**
     * @dev Initializes the contract connected to an initial authority.
     */
    constructor(address initialAuthority) {
        _setAuthority(initialAuthority);
    }

    /**
     * @dev Restricts access to a function as defined by the connected Authority for this contract and the
     * caller and selector of the function that entered the contract.
     *
     * [IMPORTANT]
     * ====
     * In general, this modifier should only be used on `external` functions. It is okay to use it on `public`
     * functions that are used as external entry points and are not called internally. Unless you know what you're
     * doing, it should never be used on `internal` functions. Failure to follow these rules can have critical security
     * implications! This is because the permissions are determined by the function that entered the contract, i.e. the
     * function at the bottom of the call stack, and not the function where the modifier is visible in the source code.
     * ====
     *
     * [WARNING]
     * ====
     * Avoid adding this modifier to the https://docs.soliditylang.org/en/v0.8.20/contracts.html#receive-ether-function[`receive()`]
     * function or the https://docs.soliditylang.org/en/v0.8.20/contracts.html#fallback-function[`fallback()`]. These
     * functions are the only execution paths where a function selector cannot be unambiguously determined from the calldata
     * since the selector defaults to `0x00000000` in the `receive()` function and similarly in the `fallback()` function
     * if no calldata is provided. (See {_checkCanCall}).
     *
     * The `receive()` function will always panic whereas the `fallback()` may panic depending on the calldata length.
     * ====
     */
    modifier restricted() {
        _checkCanCall(_msgSender(), _msgData());
        _;
    }

    /// @inheritdoc IAccessManaged
    function authority() public view virtual returns (address) {
        return _authority;
    }

    /// @inheritdoc IAccessManaged
    function setAuthority(address newAuthority) public virtual {
        address caller = _msgSender();
        if (caller != authority()) {
            revert AccessManagedUnauthorized(caller);
        }
        if (newAuthority.code.length == 0) {
            revert AccessManagedInvalidAuthority(newAuthority);
        }
        _setAuthority(newAuthority);
    }

    /// @inheritdoc IAccessManaged
    function isConsumingScheduledOp() public view returns (bytes4) {
        return _consumingSchedule ? this.isConsumingScheduledOp.selector : bytes4(0);
    }

    /**
     * @dev Transfers control to a new authority. Internal function with no access restriction. Allows bypassing the
     * permissions set by the current authority.
     */
    function _setAuthority(address newAuthority) internal virtual {
        _authority = newAuthority;
        emit AuthorityUpdated(newAuthority);
    }

    /**
     * @dev Reverts if the caller is not allowed to call the function identified by a selector. Panics if the calldata
     * is less than 4 bytes long.
     */
    function _checkCanCall(address caller, bytes calldata data) internal virtual {
        (bool immediate, uint32 delay) = AuthorityUtils.canCallWithDelay(
            authority(),
            caller,
            address(this),
            bytes4(data[0:4])
        );
        if (!immediate) {
            if (delay > 0) {
                _consumingSchedule = true;
                IAccessManager(authority()).consumeScheduledOp(caller, data);
                _consumingSchedule = false;
            } else {
                revert AccessManagedUnauthorized(caller);
            }
        }
    }
}

npm/@openzeppelin/[email protected]/access/manager/AuthorityUtils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (access/manager/AuthorityUtils.sol)

pragma solidity ^0.8.20;

import {IAuthority} from "./IAuthority.sol";

library AuthorityUtils {
    /**
     * @dev Since `AccessManager` implements an extended IAuthority interface, invoking `canCall` with backwards compatibility
     * for the preexisting `IAuthority` interface requires special care to avoid reverting on insufficient return data.
     * This helper function takes care of invoking `canCall` in a backwards compatible way without reverting.
     */
    function canCallWithDelay(
        address authority,
        address caller,
        address target,
        bytes4 selector
    ) internal view returns (bool immediate, uint32 delay) {
        bytes memory data = abi.encodeCall(IAuthority.canCall, (caller, target, selector));

        assembly ("memory-safe") {
            mstore(0x00, 0x00)
            mstore(0x20, 0x00)

            if staticcall(gas(), authority, add(data, 0x20), mload(data), 0x00, 0x40) {
                immediate := mload(0x00)
                delay := mload(0x20)

                // If delay does not fit in a uint32, return 0 (no delay)
                // equivalent to: if gt(delay, 0xFFFFFFFF) { delay := 0 }
                delay := mul(delay, iszero(shr(32, delay)))
            }
        }
    }
}

npm/@openzeppelin/[email protected]/access/manager/IAccessManaged.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/manager/IAccessManaged.sol)

pragma solidity >=0.8.4;

interface IAccessManaged {
    /**
     * @dev Authority that manages this contract was updated.
     */
    event AuthorityUpdated(address authority);

    error AccessManagedUnauthorized(address caller);
    error AccessManagedRequiredDelay(address caller, uint32 delay);
    error AccessManagedInvalidAuthority(address authority);

    /**
     * @dev Returns the current authority.
     */
    function authority() external view returns (address);

    /**
     * @dev Transfers control to a new authority. The caller must be the current authority.
     */
    function setAuthority(address) external;

    /**
     * @dev Returns true only in the context of a delayed restricted call, at the moment that the scheduled operation is
     * being consumed. Prevents denial of service for delayed restricted calls in the case that the contract performs
     * attacker controlled calls.
     */
    function isConsumingScheduledOp() external view returns (bytes4);
}

npm/@openzeppelin/[email protected]/access/manager/IAccessManager.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/manager/IAccessManager.sol)

pragma solidity >=0.8.4;

interface IAccessManager {
    /**
     * @dev A delayed operation was scheduled.
     */
    event OperationScheduled(
        bytes32 indexed operationId,
        uint32 indexed nonce,
        uint48 schedule,
        address caller,
        address target,
        bytes data
    );

    /**
     * @dev A scheduled operation was executed.
     */
    event OperationExecuted(bytes32 indexed operationId, uint32 indexed nonce);

    /**
     * @dev A scheduled operation was canceled.
     */
    event OperationCanceled(bytes32 indexed operationId, uint32 indexed nonce);

    /**
     * @dev Informational labelling for a roleId.
     */
    event RoleLabel(uint64 indexed roleId, string label);

    /**
     * @dev Emitted when `account` is granted `roleId`.
     *
     * NOTE: The meaning of the `since` argument depends on the `newMember` argument.
     * If the role is granted to a new member, the `since` argument indicates when the account becomes a member of the role,
     * otherwise it indicates the execution delay for this account and roleId is updated.
     */
    event RoleGranted(uint64 indexed roleId, address indexed account, uint32 delay, uint48 since, bool newMember);

    /**
     * @dev Emitted when `account` membership or `roleId` is revoked. Unlike granting, revoking is instantaneous.
     */
    event RoleRevoked(uint64 indexed roleId, address indexed account);

    /**
     * @dev Role acting as admin over a given `roleId` is updated.
     */
    event RoleAdminChanged(uint64 indexed roleId, uint64 indexed admin);

    /**
     * @dev Role acting as guardian over a given `roleId` is updated.
     */
    event RoleGuardianChanged(uint64 indexed roleId, uint64 indexed guardian);

    /**
     * @dev Grant delay for a given `roleId` will be updated to `delay` when `since` is reached.
     */
    event RoleGrantDelayChanged(uint64 indexed roleId, uint32 delay, uint48 since);

    /**
     * @dev Target mode is updated (true = closed, false = open).
     */
    event TargetClosed(address indexed target, bool closed);

    /**
     * @dev Role required to invoke `selector` on `target` is updated to `roleId`.
     */
    event TargetFunctionRoleUpdated(address indexed target, bytes4 selector, uint64 indexed roleId);

    /**
     * @dev Admin delay for a given `target` will be updated to `delay` when `since` is reached.
     */
    event TargetAdminDelayUpdated(address indexed target, uint32 delay, uint48 since);

    error AccessManagerAlreadyScheduled(bytes32 operationId);
    error AccessManagerNotScheduled(bytes32 operationId);
    error AccessManagerNotReady(bytes32 operationId);
    error AccessManagerExpired(bytes32 operationId);
    error AccessManagerLockedRole(uint64 roleId);
    error AccessManagerBadConfirmation();
    error AccessManagerUnauthorizedAccount(address msgsender, uint64 roleId);
    error AccessManagerUnauthorizedCall(address caller, address target, bytes4 selector);
    error AccessManagerUnauthorizedConsume(address target);
    error AccessManagerUnauthorizedCancel(address msgsender, address caller, address target, bytes4 selector);
    error AccessManagerInvalidInitialAdmin(address initialAdmin);

    /**
     * @dev Check if an address (`caller`) is authorised to call a given function on a given contract directly (with
     * no restriction). Additionally, it returns the delay needed to perform the call indirectly through the {schedule}
     * & {execute} workflow.
     *
     * This function is usually called by the targeted contract to control immediate execution of restricted functions.
     * Therefore we only return true if the call can be performed without any delay. If the call is subject to a
     * previously set delay (not zero), then the function should return false and the caller should schedule the operation
     * for future execution.
     *
     * If `allowed` is true, the delay can be disregarded and the operation can be immediately executed, otherwise
     * the operation can be executed if and only if delay is greater than 0.
     *
     * NOTE: The IAuthority interface does not include the `uint32` delay. This is an extension of that interface that
     * is backward compatible. Some contracts may thus ignore the second return argument. In that case they will fail
     * to identify the indirect workflow, and will consider calls that require a delay to be forbidden.
     *
     * NOTE: This function does not report the permissions of the admin functions in the manager itself. These are defined by the
     * {AccessManager} documentation.
     */
    function canCall(
        address caller,
        address target,
        bytes4 selector
    ) external view returns (bool allowed, uint32 delay);

    /**
     * @dev Expiration delay for scheduled proposals. Defaults to 1 week.
     *
     * IMPORTANT: Avoid overriding the expiration with 0. Otherwise every contract proposal will be expired immediately,
     * disabling any scheduling usage.
     */
    function expiration() external view returns (uint32);

    /**
     * @dev Minimum setback for all delay updates, with the exception of execution delays. It
     * can be increased without setback (and reset via {revokeRole} in the case event of an
     * accidental increase). Defaults to 5 days.
     */
    function minSetback() external view returns (uint32);

    /**
     * @dev Get whether the contract is closed disabling any access. Otherwise role permissions are applied.
     *
     * NOTE: When the manager itself is closed, admin functions are still accessible to avoid locking the contract.
     */
    function isTargetClosed(address target) external view returns (bool);

    /**
     * @dev Get the role required to call a function.
     */
    function getTargetFunctionRole(address target, bytes4 selector) external view returns (uint64);

    /**
     * @dev Get the admin delay for a target contract. Changes to contract configuration are subject to this delay.
     */
    function getTargetAdminDelay(address target) external view returns (uint32);

    /**
     * @dev Get the id of the role that acts as an admin for the given role.
     *
     * The admin permission is required to grant the role, revoke the role and update the execution delay to execute
     * an operation that is restricted to this role.
     */
    function getRoleAdmin(uint64 roleId) external view returns (uint64);

    /**
     * @dev Get the role that acts as a guardian for a given role.
     *
     * The guardian permission allows canceling operations that have been scheduled under the role.
     */
    function getRoleGuardian(uint64 roleId) external view returns (uint64);

    /**
     * @dev Get the role current grant delay.
     *
     * Its value may change at any point without an event emitted following a call to {setGrantDelay}.
     * Changes to this value, including effect timepoint are notified in advance by the {RoleGrantDelayChanged} event.
     */
    function getRoleGrantDelay(uint64 roleId) external view returns (uint32);

    /**
     * @dev Get the access details for a given account for a given role. These details include the timepoint at which
     * membership becomes active, and the delay applied to all operation by this user that requires this permission
     * level.
     *
     * Returns:
     * [0] Timestamp at which the account membership becomes valid. 0 means role is not granted.
     * [1] Current execution delay for the account.
     * [2] Pending execution delay for the account.
     * [3] Timestamp at which the pending execution delay will become active. 0 means no delay update is scheduled.
     */
    function getAccess(
        uint64 roleId,
        address account
    ) external view returns (uint48 since, uint32 currentDelay, uint32 pendingDelay, uint48 effect);

    /**
     * @dev Check if a given account currently has the permission level corresponding to a given role. Note that this
     * permission might be associated with an execution delay. {getAccess} can provide more details.
     */
    function hasRole(uint64 roleId, address account) external view returns (bool isMember, uint32 executionDelay);

    /**
     * @dev Give a label to a role, for improved role discoverability by UIs.
     *
     * Requirements:
     *
     * - the caller must be a global admin
     *
     * Emits a {RoleLabel} event.
     */
    function labelRole(uint64 roleId, string calldata label) external;

    /**
     * @dev Add `account` to `roleId`, or change its execution delay.
     *
     * This gives the account the authorization to call any function that is restricted to this role. An optional
     * execution delay (in seconds) can be set. If that delay is non 0, the user is required to schedule any operation
     * that is restricted to members of this role. The user will only be able to execute the operation after the delay has
     * passed, before it has expired. During this period, admin and guardians can cancel the operation (see {cancel}).
     *
     * If the account has already been granted this role, the execution delay will be updated. This update is not
     * immediate and follows the delay rules. For example, if a user currently has a delay of 3 hours, and this is
     * called to reduce that delay to 1 hour, the new delay will take some time to take effect, enforcing that any
     * operation executed in the 3 hours that follows this update was indeed scheduled before this update.
     *
     * Requirements:
     *
     * - the caller must be an admin for the role (see {getRoleAdmin})
     * - granted role must not be the `PUBLIC_ROLE`
     *
     * Emits a {RoleGranted} event.
     */
    function grantRole(uint64 roleId, address account, uint32 executionDelay) external;

    /**
     * @dev Remove an account from a role, with immediate effect. If the account does not have the role, this call has
     * no effect.
     *
     * Requirements:
     *
     * - the caller must be an admin for the role (see {getRoleAdmin})
     * - revoked role must not be the `PUBLIC_ROLE`
     *
     * Emits a {RoleRevoked} event if the account had the role.
     */
    function revokeRole(uint64 roleId, address account) external;

    /**
     * @dev Renounce role permissions for the calling account with immediate effect. If the sender is not in
     * the role this call has no effect.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * Emits a {RoleRevoked} event if the account had the role.
     */
    function renounceRole(uint64 roleId, address callerConfirmation) external;

    /**
     * @dev Change admin role for a given role.
     *
     * Requirements:
     *
     * - the caller must be a global admin
     *
     * Emits a {RoleAdminChanged} event
     */
    function setRoleAdmin(uint64 roleId, uint64 admin) external;

    /**
     * @dev Change guardian role for a given role.
     *
     * Requirements:
     *
     * - the caller must be a global admin
     *
     * Emits a {RoleGuardianChanged} event
     */
    function setRoleGuardian(uint64 roleId, uint64 guardian) external;

    /**
     * @dev Update the delay for granting a `roleId`.
     *
     * Requirements:
     *
     * - the caller must be a global admin
     *
     * Emits a {RoleGrantDelayChanged} event.
     */
    function setGrantDelay(uint64 roleId, uint32 newDelay) external;

    /**
     * @dev Set the role required to call functions identified by the `selectors` in the `target` contract.
     *
     * Requirements:
     *
     * - the caller must be a global admin
     *
     * Emits a {TargetFunctionRoleUpdated} event per selector.
     */
    function setTargetFunctionRole(address target, bytes4[] calldata selectors, uint64 roleId) external;

    /**
     * @dev Set the delay for changing the configuration of a given target contract.
     *
     * Requirements:
     *
     * - the caller must be a global admin
     *
     * Emits a {TargetAdminDelayUpdated} event.
     */
    function setTargetAdminDelay(address target, uint32 newDelay) external;

    /**
     * @dev Set the closed flag for a contract.
     *
     * Closing the manager itself won't disable access to admin methods to avoid locking the contract.
     *
     * Requirements:
     *
     * - the caller must be a global admin
     *
     * Emits a {TargetClosed} event.
     */
    function setTargetClosed(address target, bool closed) external;

    /**
     * @dev Return the timepoint at which a scheduled operation will be ready for execution. This returns 0 if the
     * operation is not yet scheduled, has expired, was executed, or was canceled.
     */
    function getSchedule(bytes32 id) external view returns (uint48);

    /**
     * @dev Return the nonce for the latest scheduled operation with a given id. Returns 0 if the operation has never
     * been scheduled.
     */
    function getNonce(bytes32 id) external view returns (uint32);

    /**
     * @dev Schedule a delayed operation for future execution, and return the operation identifier. It is possible to
     * choose the timestamp at which the operation becomes executable as long as it satisfies the execution delays
     * required for the caller. The special value zero will automatically set the earliest possible time.
     *
     * Returns the `operationId` that was scheduled. Since this value is a hash of the parameters, it can reoccur when
     * the same parameters are used; if this is relevant, the returned `nonce` can be used to uniquely identify this
     * scheduled operation from other occurrences of the same `operationId` in invocations of {execute} and {cancel}.
     *
     * Emits a {OperationScheduled} event.
     *
     * NOTE: It is not possible to concurrently schedule more than one operation with the same `target` and `data`. If
     * this is necessary, a random byte can be appended to `data` to act as a salt that will be ignored by the target
     * contract if it is using standard Solidity ABI encoding.
     */
    function schedule(
        address target,
        bytes calldata data,
        uint48 when
    ) external returns (bytes32 operationId, uint32 nonce);

    /**
     * @dev Execute a function that is delay restricted, provided it was properly scheduled beforehand, or the
     * execution delay is 0.
     *
     * Returns the nonce that identifies the previously scheduled operation that is executed, or 0 if the
     * operation wasn't previously scheduled (if the caller doesn't have an execution delay).
     *
     * Emits an {OperationExecuted} event only if the call was scheduled and delayed.
     */
    function execute(address target, bytes calldata data) external payable returns (uint32);

    /**
     * @dev Cancel a scheduled (delayed) operation. Returns the nonce that identifies the previously scheduled
     * operation that is cancelled.
     *
     * Requirements:
     *
     * - the caller must be the proposer, a guardian of the targeted function, or a global admin
     *
     * Emits a {OperationCanceled} event.
     */
    function cancel(address caller, address target, bytes calldata data) external returns (uint32);

    /**
     * @dev Consume a scheduled operation targeting the caller. If such an operation exists, mark it as consumed
     * (emit an {OperationExecuted} event and clean the state). Otherwise, throw an error.
     *
     * This is useful for contract that want to enforce that calls targeting them were scheduled on the manager,
     * with all the verifications that it implies.
     *
     * Emit a {OperationExecuted} event.
     */
    function consumeScheduledOp(address caller, bytes calldata data) external;

    /**
     * @dev Hashing function for delayed operations.
     */
    function hashOperation(address caller, address target, bytes calldata data) external view returns (bytes32);

    /**
     * @dev Changes the authority of a target managed by this manager instance.
     *
     * Requirements:
     *
     * - the caller must be a global admin
     */
    function updateAuthority(address target, address newAuthority) external;
}

npm/@openzeppelin/[email protected]/access/manager/IAuthority.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/manager/IAuthority.sol)

pragma solidity >=0.4.16;

/**
 * @dev Standard interface for permissioning originally defined in Dappsys.
 */
interface IAuthority {
    /**
     * @dev Returns true if the caller can invoke on a target the function identified by a function selector.
     */
    function canCall(address caller, address target, bytes4 selector) external view returns (bool allowed);
}

npm/@openzeppelin/[email protected]/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

import {IERC20} from "../token/ERC20/IERC20.sol";

npm/@openzeppelin/[email protected]/interfaces/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20Metadata.sol)

pragma solidity >=0.6.2;

import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";

npm/@openzeppelin/[email protected]/proxy/Clones.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/Clones.sol)

pragma solidity ^0.8.20;

import {Create2} from "../utils/Create2.sol";
import {Errors} from "../utils/Errors.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[ERC-1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 */
library Clones {
    error CloneArgumentsTooLong();

    /**
     * @dev Deploys and returns the address of a clone that mimics the behavior of `implementation`.
     *
     * This function uses the create opcode, which should never revert.
     *
     * WARNING: This function does not check if `implementation` has code. A clone that points to an address
     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
     */
    function clone(address implementation) internal returns (address instance) {
        return clone(implementation, 0);
    }

    /**
     * @dev Same as {xref-Clones-clone-address-}[clone], but with a `value` parameter to send native currency
     * to the new contract.
     *
     * WARNING: This function does not check if `implementation` has code. A clone that points to an address
     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
     *
     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
     * to always have enough balance for new deployments. Consider exposing this function under a payable method.
     */
    function clone(address implementation, uint256 value) internal returns (address instance) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        assembly ("memory-safe") {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create(value, 0x09, 0x37)
        }
        if (instance == address(0)) {
            revert Errors.FailedDeployment();
        }
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behavior of `implementation`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `implementation` and `salt` multiple times will revert, since
     * the clones cannot be deployed twice at the same address.
     *
     * WARNING: This function does not check if `implementation` has code. A clone that points to an address
     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
     */
    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
        return cloneDeterministic(implementation, salt, 0);
    }

    /**
     * @dev Same as {xref-Clones-cloneDeterministic-address-bytes32-}[cloneDeterministic], but with
     * a `value` parameter to send native currency to the new contract.
     *
     * WARNING: This function does not check if `implementation` has code. A clone that points to an address
     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
     *
     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
     * to always have enough balance for new deployments. Consider exposing this function under a payable method.
     */
    function cloneDeterministic(
        address implementation,
        bytes32 salt,
        uint256 value
    ) internal returns (address instance) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        assembly ("memory-safe") {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create2(value, 0x09, 0x37, salt)
        }
        if (instance == address(0)) {
            revert Errors.FailedDeployment();
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            mstore(add(ptr, 0x38), deployer)
            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
            mstore(add(ptr, 0x14), implementation)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
            mstore(add(ptr, 0x58), salt)
            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
            predicted := and(keccak256(add(ptr, 0x43), 0x55), 0xffffffffffffffffffffffffffffffffffffffff)
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt
    ) internal view returns (address predicted) {
        return predictDeterministicAddress(implementation, salt, address(this));
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behavior of `implementation` with custom
     * immutable arguments. These are provided through `args` and cannot be changed after deployment. To
     * access the arguments within the implementation, use {fetchCloneArgs}.
     *
     * This function uses the create opcode, which should never revert.
     *
     * WARNING: This function does not check if `implementation` has code. A clone that points to an address
     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
     */
    function cloneWithImmutableArgs(address implementation, bytes memory args) internal returns (address instance) {
        return cloneWithImmutableArgs(implementation, args, 0);
    }

    /**
     * @dev Same as {xref-Clones-cloneWithImmutableArgs-address-bytes-}[cloneWithImmutableArgs], but with a `value`
     * parameter to send native currency to the new contract.
     *
     * WARNING: This function does not check if `implementation` has code. A clone that points to an address
     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
     *
     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
     * to always have enough balance for new deployments. Consider exposing this function under a payable method.
     */
    function cloneWithImmutableArgs(
        address implementation,
        bytes memory args,
        uint256 value
    ) internal returns (address instance) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);
        assembly ("memory-safe") {
            instance := create(value, add(bytecode, 0x20), mload(bytecode))
        }
        if (instance == address(0)) {
            revert Errors.FailedDeployment();
        }
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behavior of `implementation` with custom
     * immutable arguments. These are provided through `args` and cannot be changed after deployment. To
     * access the arguments within the implementation, use {fetchCloneArgs}.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy the clone. Using the same
     * `implementation`, `args` and `salt` multiple times will revert, since the clones cannot be deployed twice
     * at the same address.
     *
     * WARNING: This function does not check if `implementation` has code. A clone that points to an address
     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
     */
    function cloneDeterministicWithImmutableArgs(
        address implementation,
        bytes memory args,
        bytes32 salt
    ) internal returns (address instance) {
        return cloneDeterministicWithImmutableArgs(implementation, args, salt, 0);
    }

    /**
     * @dev Same as {xref-Clones-cloneDeterministicWithImmutableArgs-address-bytes-bytes32-}[cloneDeterministicWithImmutableArgs],
     * but with a `value` parameter to send native currency to the new contract.
     *
     * WARNING: This function does not check if `implementation` has code. A clone that points to an address
     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
     *
     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
     * to always have enough balance for new deployments. Consider exposing this function under a payable method.
     */
    function cloneDeterministicWithImmutableArgs(
        address implementation,
        bytes memory args,
        bytes32 salt,
        uint256 value
    ) internal returns (address instance) {
        bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);
        return Create2.deploy(value, salt, bytecode);
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministicWithImmutableArgs}.
     */
    function predictDeterministicAddressWithImmutableArgs(
        address implementation,
        bytes memory args,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);
        return Create2.computeAddress(salt, keccak256(bytecode), deployer);
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministicWithImmutableArgs}.
     */
    function predictDeterministicAddressWithImmutableArgs(
        address implementation,
        bytes memory args,
        bytes32 salt
    ) internal view returns (address predicted) {
        return predictDeterministicAddressWithImmutableArgs(implementation, args, salt, address(this));
    }

    /**
     * @dev Get the immutable args attached to a clone.
     *
     * - If `instance` is a clone that was deployed using `clone` or `cloneDeterministic`, this
     *   function will return an empty array.
     * - If `instance` is a clone that was deployed using `cloneWithImmutableArgs` or
     *   `cloneDeterministicWithImmutableArgs`, this function will return the args array used at
     *   creation.
     * - If `instance` is NOT a clone deployed using this library, the behavior is undefined. This
     *   function should only be used to check addresses that are known to be clones.
     */
    function fetchCloneArgs(address instance) internal view returns (bytes memory) {
        bytes memory result = new bytes(instance.code.length - 45); // revert if length is too short
        assembly ("memory-safe") {
            extcodecopy(instance, add(result, 32), 45, mload(result))
        }
        return result;
    }

    /**
     * @dev Helper that prepares the initcode of the proxy with immutable args.
     *
     * An assembly variant of this function requires copying the `args` array, which can be efficiently done using
     * `mcopy`. Unfortunately, that opcode is not available before cancun. A pure solidity implementation using
     * abi.encodePacked is more expensive but also more portable and easier to review.
     *
     * NOTE: https://eips.ethereum.org/EIPS/eip-170[EIP-170] limits the length of the contract code to 24576 bytes.
     * With the proxy code taking 45 bytes, that limits the length of the immutable args to 24531 bytes.
     */
    function _cloneCodeWithImmutableArgs(
        address implementation,
        bytes memory args
    ) private pure returns (bytes memory) {
        if (args.length > 24531) revert CloneArgumentsTooLong();
        return
            abi.encodePacked(
                hex"61",
                uint16(args.length + 45),
                hex"3d81600a3d39f3363d3d373d3d3d363d73",
                implementation,
                hex"5af43d82803e903d91602b57fd5bf3",
                args
            );
    }
}

npm/@openzeppelin/[email protected]/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

npm/@openzeppelin/[email protected]/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity >=0.6.2;

import {IERC20} from "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

npm/@openzeppelin/[email protected]/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

npm/@openzeppelin/[email protected]/utils/Create2.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Create2.sol)

pragma solidity ^0.8.20;

import {Errors} from "./Errors.sol";

/**
 * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
 * `CREATE2` can be used to compute in advance the address where a smart
 * contract will be deployed, which allows for interesting new mechanisms known
 * as 'counterfactual interactions'.
 *
 * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
 * information.
 */
library Create2 {
    /**
     * @dev There's no code to deploy.
     */
    error Create2EmptyBytecode();

    /**
     * @dev Deploys a contract using `CREATE2`. The address where the contract
     * will be deployed can be known in advance via {computeAddress}.
     *
     * The bytecode for a contract can be obtained from Solidity with
     * `type(contractName).creationCode`.
     *
     * Requirements:
     *
     * - `bytecode` must not be empty.
     * - `salt` must have not been used for `bytecode` already.
     * - the factory must have a balance of at least `amount`.
     * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
     */
    function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }
        if (bytecode.length == 0) {
            revert Create2EmptyBytecode();
        }
        assembly ("memory-safe") {
            addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
            // if no address was created, and returndata is not empty, bubble revert
            if and(iszero(addr), not(iszero(returndatasize()))) {
                let p := mload(0x40)
                returndatacopy(p, 0, returndatasize())
                revert(p, returndatasize())
            }
        }
        if (addr == address(0)) {
            revert Errors.FailedDeployment();
        }
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
     * `bytecodeHash` or `salt` will result in a new destination address.
     */
    function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
        return computeAddress(salt, bytecodeHash, address(this));
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
     * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
     */
    function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {
        assembly ("memory-safe") {
            let ptr := mload(0x40) // Get free memory pointer

            // |                   | ↓ ptr ...  ↓ ptr + 0x0B (start) ...  ↓ ptr + 0x20 ...  ↓ ptr + 0x40 ...   |
            // |-------------------|---------------------------------------------------------------------------|
            // | bytecodeHash      |                                                        CCCCCCCCCCCCC...CC |
            // | salt              |                                      BBBBBBBBBBBBB...BB                   |
            // | deployer          | 000000...0000AAAAAAAAAAAAAAAAAAA...AA                                     |
            // | 0xFF              |            FF                                                             |
            // |-------------------|---------------------------------------------------------------------------|
            // | memory            | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |
            // | keccak(start, 85) |            ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |

            mstore(add(ptr, 0x40), bytecodeHash)
            mstore(add(ptr, 0x20), salt)
            mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes
            let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff
            mstore8(start, 0xff)
            addr := and(keccak256(start, 85), 0xffffffffffffffffffffffffffffffffffffffff)
        }
    }
}

npm/@openzeppelin/[email protected]/utils/Errors.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

project/contracts/interfaces/IClearFactory.sol

// SPDX-License-Identifier: MIT

//████████╗██████╗ ███████╗██╗   ██╗███████╗███████╗
//╚══██╔══╝██╔══██╗██╔════╝██║   ██║██╔════╝██╔════╝
//   ██║   ██████╔╝█████╗  ██║   ██║█████╗  █████╗
//   ██║   ██╔══██╗██╔══╝  ╚██╗ ██╔╝██╔══╝  ██╔══╝
//   ██║   ██║  ██║███████╗ ╚████╔╝ ███████╗███████╗
//   ╚═╝   ╚═╝  ╚═╝╚══════╝  ╚═══╝  ╚══════╝╚══════╝

pragma solidity ^0.8.24;

import "@openzeppelin/contracts/interfaces/IERC20.sol";
import "@openzeppelin/contracts/interfaces/IERC20Metadata.sol";

/**
 * @title IClearFactory
 * @notice Interface for the Clear protocol's factory contract
 * @dev Defines functions for deploying vaults, managing configurations, and upgrading implementations
 * @author Clear Protocol Team
 */
interface IClearFactory  {

    /// @notice Thrown when the factory is not properly initialized
    error NotInitialized();

    /// @notice Thrown when a vault address is invalid
    error InvalidVaultAddress(address _address);

    /// @notice Thrown when attempting to use a rebalance target that has not been authorized
    error UnauthorizedRebalanceTarget();


    /// @notice Emitted when a new Clear vault is deployed
    /// @param index The index of the new vault in the registry
    /// @param implementation The vault implementation address used
    /// @param vault The address of the deployed vault proxy
    /// @param name The name of the vault token
    /// @param symbol The symbol of the vault token
    event NewClearVault(
        uint256 indexed index,
        address indexed implementation,
        address vault,
        string name,
        string symbol,
        address[] tokens,
        address curvePlainPool
    );
    
    /// @notice Emitted when the vault implementation is upgraded
    /// @param version The new version number
    /// @param implementation The new implementation address
    event NewVaultImplementation(uint256 indexed version, address implementation);
    
    /// @notice Emitted when the IOU implementation is upgraded
    /// @param version The new version number
    /// @param implementation The new implementation address
    event NewIOUImplementation(uint256 indexed version, address implementation);


    /**
     * @notice Deploys a new ClearVault proxy along with a Curve plain pool for its tokens
     * @param _name The name for the vault's ERC20 share token
     * @param _symbol The symbol for the vault's ERC20 share token
     * @param _plainPoolName The name for the Curve plain pool
     * @param _plainPoolSymbol The symbol for the Curve plain pool
     * @param _tokens Array of ERC20 token addresses to support in the new vault
     */
    function deployNewVault(
        string memory _name,
        string memory _symbol,
        string memory _plainPoolName,
        string memory _plainPoolSymbol,
        address[] memory _tokens
    ) external;

    /**
     * @notice Initializes a token in an existing vault by deploying its IOU token and Curve meta pool
     * @param _vault The vault address to initialize the token in
     * @param _token The underlying ERC20 token address to configure
     * @param _adapter The ERC4626 yield adapter address for the token
     * @param _desiredExposureBps Desired token exposure in basis points (10000 = 100%)
     * @param _maxExposureBps Maximum allowed token exposure in basis points (10000 = 100%)
     * @param _iouName The name of the IOU ERC20 token to deploy
     * @param _iouSymbol The symbol of the IOU ERC20 token to deploy
     * @param _metaPoolName The name for the Curve IOU meta pool
     * @param _metaPoolSymbol The symbol for the Curve IOU meta pool
     */
    function initializeToken(
        address _vault,
        address _token,
        address _adapter,
        uint256 _desiredExposureBps,
        uint256 _maxExposureBps,
        string memory _iouName,
        string memory _iouSymbol,
        string memory _metaPoolName,
        string memory _metaPoolSymbol
    ) external;

    /**
     * @notice Sets the exposure configuration for a token in a vault
     * @dev Updates the desired and maximum exposure limits for vault rebalancing
     * @param _vault The vault address
     * @param _token The token address
     * @param _newDesiredExposureBps The new desired exposure in basis points
     * @param _newMaximalExposureBps The new maximum exposure in basis points
     */
    function setTokenExposureConfiguration(
        address _vault, 
        address _token, 
        uint256 _newDesiredExposureBps,
        uint256 _newMaximalExposureBps
    ) external;

    /**
     * @notice Sets the maximum rebalance spread for a vault
     * @dev Updates the maximum allowed slippage during rebalancing operations
     * @param _vault The vault address
     * @param _newMaximumRebalanceBpsSpread The new maximum spread in basis points
     */
    function setMaximumRebalanceBpsSpread(
        address _vault, 
        uint256 _newMaximumRebalanceBpsSpread
    ) external;

    /**
     * @notice Sets the IOU minting fee for a vault
     * @dev Updates the fee charged when IOU tokens are minted during swaps
     * @param _vault The vault address
     * @param _newLpFee The new LP fee in basis points
     * @param _newTreasuryFee The new treasury fee in basis points
     */
    function setIouFeeBps(
        address _vault, 
        uint256 _newLpFee,
        uint256 _newTreasuryFee
    ) external;

    /**
     * @notice Grants or revokes authorization for a rebalance swap target
     * @param _allowed Whether the target should be authorized (true) or revoked (false)
     * @param _target The contract address to authorize or revoke as a rebalance target
     */
    function setRebalanceTarget(bool _allowed, address _target) external;

    /**
     * @notice Upgrades the vault implementation contract
     * @dev Updates the implementation address used for new vault deployments
     * @param _implementation The new vault implementation address
     */
    function upgradeVault(address _implementation) external;
    
    /**
     * @notice Upgrades the IOU implementation contract
     * @dev Updates the implementation address used for new IOU deployments
     * @param _implementation The new IOU implementation address
     */
    function upgradeIOU(address _implementation) external;

    /**
     * @notice Gets vault addresses for multiple indices
     * @dev Returns an array of vault addresses corresponding to the provided indices
     * @param _indexes Array of vault indices to query
     * @return Array of corresponding vault addresses
     */
    function getBatchVaultAddresses(
        uint256[] memory _indexes
    ) external view returns (address[] memory);

    /**
     * @notice Check if the address is a vault created by this factory
     * @dev indicating if the address is a vault created by this factory
     * @param _address address to verify
     * @return bool indicating if the address is a vault created by this factory
     */
    function isVault(address _address) external view returns (bool);

    
}

project/contracts/interfaces/IClearIOU.sol

// SPDX-License-Identifier: MIT

//████████╗██████╗ ███████╗██╗   ██╗███████╗███████╗
//╚══██╔══╝██╔══██╗██╔════╝██║   ██║██╔════╝██╔════╝
//   ██║   ██████╔╝█████╗  ██║   ██║█████╗  █████╗
//   ██║   ██╔══██╗██╔══╝  ╚██╗ ██╔╝██╔══╝  ██╔══╝
//   ██║   ██║  ██║███████╗ ╚████╔╝ ███████╗███████╗
//   ╚═╝   ╚═╝  ╚═╝╚══════╝  ╚═══╝  ╚══════╝╚══════╝

pragma solidity ^0.8.24;

import "@openzeppelin/contracts/interfaces/IERC20.sol";
import "@openzeppelin/contracts/interfaces/IERC20Metadata.sol";

/**
 * @title IClearIOU
 * @notice Interface for Clear protocol's IOU tokens representing asset claims
 * @dev Extends ERC20 with IOU-specific functionality for minting, burning, and wrapping
 * @author Clear Protocol Team
 */
interface IClearIOU is IERC20, IERC20Metadata {
    /**
     * @notice Initializes the IOU token proxy contract
     * @dev Sets up the IOU token with all necessary addresses and ERC20 functionality
     *      Can only be called once due to initializer modifier
     * @param _authority The address of the access control authority contract
     * @param _vault The vault contract that will manage this IOU
     * @param _treasury The treasury address for fee collection
     * @param _underlying The underlying token this IOU represents
     * @param _name The name of the IOU token
     * @param _symbol The symbol of the IOU token
     */
    function initialize(
        address _authority,
        address _vault,
        address _treasury,
        address _underlying,
        string memory _name,
        string memory _symbol
    ) external;

    /**
     * @notice Mints IOU tokens during swap operations with fee distribution
     * @dev Mints tokens to receiver and treasury, only callable by authorized vault
     * @param to Address to receive the IOU tokens
     * @param amount Amount of IOU tokens to mint to the receiver
     * @param treasuryFee Amount of IOU tokens to mint to the treasury as fee
     */
    function mint(address to, uint256 amount, uint256 treasuryFee) external;
    /**
     * @notice Burns IOU tokens during redemption operations
     * @dev Burns tokens from the specified address, only callable by authorized vault
     * @param to Address from which to burn the IOU tokens
     * @param amount Amount of IOU tokens to burn
     */
    function redeemBurn(address to, uint256 amount) external;

    event ClearIOUMinted(address indexed to, uint256 amount, uint256 treasuryFee);
    event ClearIOUBurned(address indexed from, uint256 amount);
}

project/contracts/interfaces/IClearVault.sol

// SPDX-License-Identifier: MIT

//████████╗██████╗ ███████╗██╗   ██╗███████╗███████╗
//╚══██╔══╝██╔══██╗██╔════╝██║   ██║██╔════╝██╔════╝
//   ██║   ██████╔╝█████╗  ██║   ██║█████╗  █████╗
//   ██║   ██╔══██╗██╔══╝  ╚██╗ ██╔╝██╔══╝  ██╔══╝
//   ██║   ██║  ██║███████╗ ╚████╔╝ ███████╗███████╗
//   ╚═╝   ╚═╝  ╚═╝╚══════╝  ╚═══╝  ╚══════╝╚══════╝

pragma solidity ^0.8.24;

import "@openzeppelin/contracts/interfaces/IERC20.sol";
import "@openzeppelin/contracts/interfaces/IERC20Metadata.sol";

/**
 * @title IClearVault
 * @notice Interface for Clear protocol's multi-token yield vault
 * @dev Extends ERC20 with multi-token vault functionality and swap integration
 * @author Clear Protocol Team
 */
interface IClearVault is IERC20, IERC20Metadata {

    error InvalidAmount();
    error InvalidInput();
    error NoTokenDecimals(address token);
    error UnknownToken(address token);
    error BadAdapterConfiguration();
    error InvalidTokenDecimals(address token, uint8 decimals);
    error SwapExceedMaximalExposure();
    error CurvePoolNotSet();
    error UnknownRebalanceSwapError();
    error TokenAlreadyInitialized();
    error RebalanceSpreadTooHigh(uint256 amountIn, uint256 amountOut);

    /**
     * @dev Attempted to deposit more assets than the max amount for `receiver`.
     */
    error ClearVaultExceededMaxDeposit(address receiver, uint256 assets, uint256 max);

    /**
     * @dev Attempted to mint more shares than the max amount for `receiver`.
     */
    error ClearVaultExceededMaxMint(address receiver, uint256 shares, uint256 max);

    /**
     * @dev Attempted to withdraw more assets than the max amount for `receiver`.
     */
    error ClearVaultExceededMaxWithdraw(address owner, uint256 assets, uint256 max);

    /**
     * @dev Attempted to redeem more shares than the max amount for `receiver`.
     */
    error ClearVaultExceededMaxRedeem(address owner, uint256 shares, uint256 max);

    /// @notice Emitted when assets are deposited into the vault
    event Deposit(address indexed token, address indexed sender, address indexed owner, uint256 assets, uint256 shares);

    /// @notice Emitted when assets are withdrawn from the vault
    event Withdraw(
        address indexed token,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /// @notice Emitted when the vault proxy is initialized
    event VaultInitialized(
        address _initialAuthority,
        string _name,
        string _symbol,
        address _tokensCurvePool,
        address[] _tokens
    );

    /// @notice Emitted when a new token is added to the vault's allowed list
    event TokenAdded(address token);

    /// @notice Emitted when a token's yield adapter is replaced
    event AdapterChanged(address token, address newAdapter);

    /// @notice Emitted when a token's desired or maximum exposure limits are updated
    event TokenExposureConfigurationUpdated(address token, uint256 newDesiredExposureBps, uint256 newMaximalExposureBps);

    /// @notice Emitted when the maximum rebalance slippage tolerance is updated
    event MaximalRebalanceBpsSpreadUpdated(uint256 newSpread);

    /// @notice Emitted when the maximum deviation from desired exposure is updated
    event DesiredExposureMaximalBpsSpreadUpdated(uint256 newSpread);

    /// @notice Emitted when the IOU minting fee is updated
    event IouFeeBpsUpdated(uint256 lpFee, uint256 treasuryFee);

    /// @notice Emitted when the Curve IOU meta pool address is updated for a token
    event IouCurveMetaPoolUpdated(address token, address pool);

    /// @notice Emitted when a rebalance swap between two tokens is executed
    event LiquidityRebalanceExecuted(address from, address to, uint256 amountIn, uint256 amountOut);

    /// @notice Emitted when underlying tokens are directly wrapped into IOU tokens
    event ClearIOUWrapped(address indexed token, address indexed sender, address indexed receiver, uint256 amount);

    /// @notice Emitted when a liquidity swap is executed (potentially with IOU minting)
    event LiquiditySwapExecuted(
        address indexed from,
        address indexed to,
        address receiver,
        uint256 amountIn,
        uint256 tokenAmountOut,
        uint256 iouAmountOut,
        uint256 iouTreasuryFee,
        uint256 iouLpFee
    );

    /// @notice Emitted when a token is fully initialized with its IOU token, Curve pool, and adapter
    event TokenInitialized(
        address indexed token,
        address iouCurveMetaPool,
        address iou,
        address adapter,
        uint256 desiredExposureBps,
        uint256 maxExposureBps
    );

    /// @notice Internal per-token storage entry
    struct Token {
        bool enabled;           ///< Whether this token has been added to the vault
        bool initialized;       ///< Whether initializeToken() has been called for this token
        address iou;            ///< IOU token proxy address
        address iouCurveMetaPool; ///< Curve meta pool address for IOU/token trading
        uint256 tokensCurvePoolIndex; ///< Index of this token in the Curve plain pool
        address adapter;        ///< ERC4626 yield adapter address (address(0) if none)
        uint256 maxExposureBps; ///< Maximum allowed exposure in basis points
        uint256 desiredExposureBps; ///< Target exposure in basis points
        uint256 emitedIou;      ///< Total outstanding IOU tokens (net of redemptions)
        uint8 decimals;         ///< Native decimal count of this token
    }

    /// @notice Read-only view of a token's current state, returned by details()
    struct TokenDetails {
        address addr;               ///< Token contract address
        address iou;                ///< IOU token proxy address
        address iouCurveMetaPool;   ///< Curve meta pool address for IOU/token trading
        address adapter;            ///< ERC4626 yield adapter address
        uint256 maxExposureBps;     ///< Maximum allowed exposure in basis points
        uint256 desiredExposureBps; ///< Target exposure in basis points
        uint256 emitedIou;          ///< Total outstanding IOU tokens
        uint256 balance;            ///< Current token assets (adapter balance minus IOUs)
        uint256 exposure;           ///< Current exposure in basis points
        uint8 decimals;             ///< Native decimal count of this token
    }

    /// @notice Top-level vault configuration storage
    struct Configuration {
        address[] allowedTokens;   ///< Ordered list of all vault tokens
        mapping(address => Token) tokens; ///< Per-token configuration and state

        address tokensCurvePool;              ///< Curve plain pool shared by all vault tokens
        uint256 iouTreasuryFeeBps;            ///< Treasury fee on IOU minting (basis points)
        uint256 iouLpFeeBps;                  ///< LP fee on IOU minting (basis points)
        uint256 maximumRebalanceBpsSpread;    ///< Max slippage allowed during rebalancing
        uint256 desiredExposureMaximalBpsSpread; ///< Max deviation from desired exposure
    }

    /**
     * @notice Initializes the vault proxy with access control, ERC20 metadata, and initial tokens
     * @param _initialAuthority The access control authority contract address
     * @param _name The name for the vault's ERC20 share token
     * @param _symbol The symbol for the vault's ERC20 share token
     * @param _tokensCurvePool The Curve plain pool address for multi-token swaps
     * @param _tokens Array of ERC20 token addresses to support in this vault
     */
    function initialize(
        address _initialAuthority,
        string memory _name,
        string memory _symbol,
        address _tokensCurvePool,
        address[] memory _tokens
    ) external;

    /**
     * @notice Completes token setup by associating its IOU token, Curve meta pool, and adapter
     * @param _token The underlying token address to initialize
     * @param _iou The IOU token proxy address
     * @param _iouCurveMetaPool The Curve meta pool address for IOU/token trading
     * @param _adapter The ERC4626 yield adapter address
     * @param _desiredExposureBps Desired exposure in basis points (10000 = 100%)
     * @param _maxExposureBps Maximum allowed exposure in basis points (10000 = 100%)
     */
    function initializeToken(
        address _token,
        address _iou,
        address _iouCurveMetaPool,
        address _adapter,
        uint256 _desiredExposureBps,
        uint256 _maxExposureBps
    ) external;

    /// @notice Returns the Curve plain pool address shared by all vault tokens
    function tokensCurvePool() external view returns (address);

    /// @notice Returns the zero-based index of a token in the Curve plain pool
    /// @param _token The token address to query (must be enabled)
    function tokensCurvePoolIndexOf(address _token) external view returns (uint256);

    /// @notice Returns the Curve IOU meta pool address for a given token
    /// @param _token The underlying token address (must be enabled)
    function tokenCurveMetaPool(address _token) external view returns (address);
    /**
     * @notice Changes the yield adapter for a specific token
     * @dev Withdraws all funds from current adapter and deposits into new one
     *      Only callable by factory for enabled tokens
     * @param _token The token whose adapter to change
     * @param _newAdapter The new adapter contract address
     */
    function changeAdapter(address _token, address _newAdapter) external;
    /**
     * @notice Updates exposure configuration for a specific token
     * @dev Sets the desired and maximum exposure limits for vault rebalancing
     * @param _token The token address to configure
     * @param _newDesiredExposureBps New desired exposure in basis points (10000 = 100%)
     * @param _newMaximalExposureBps New maximum exposure in basis points (10000 = 100%)
     */
    function setTokenExposureConfiguration(
        address _token, 
        uint256 _newDesiredExposureBps,
        uint256 _newMaximalExposureBps
    ) external;
    /**
     * @notice Returns the maximum exposure limit for a specific token
     * @dev Gets the maximum percentage of vault assets that can be this token
     * @param _token The token address to query
     * @return desiredExposureBps Desired exposure in basis points (10000 = 100%)
     * @return maxExposureBps Maximum exposure in basis points (10000 = 100%)
     */
    function exposureConfigurationOf(address _token) external view returns (uint256 desiredExposureBps, uint256 maxExposureBps);
    
    /**
     * @notice Returns the specified token exposure
     * @dev Gets the current exposure of specific token
     * @param _token The token address to query
     * @return exposure Current exposure in basis points (10000 = 100%)
     */
    function exposureOf(address _token) external view returns (uint256 exposure);
    /**
     * @notice Updates the maximum allowed slippage for rebalancing operations
     * @dev Sets tolerance for price impact during automated rebalancing swaps
     * @param _newMaximumRebalanceBpsSpread Maximum spread in basis points (10000 = 100%)
     */
    function setMaximumRebalanceBpsSpread(uint256 _newMaximumRebalanceBpsSpread) external;
    /**
     * @notice Updates the maximum spread from desired exposure before rebalancing triggers
     * @dev Sets the tolerance for exposure deviation that determines when vault is balanced
     * @param _newDesiredExposureMaximalBpsSpread Maximum deviation from desired exposure in basis points
     */
    function setDesiredExposureMaximalBpsSpread(uint256 _newDesiredExposureMaximalBpsSpread) external;
    /**
     * @notice Returns the maximum allowed slippage for rebalancing operations
     * @dev Gets the current tolerance for price impact during rebalancing
     * @return The maximum spread in basis points
     */
    function maximumRebalanceBpsSpread() external view returns (uint256);
    /**
     * @notice Returns the maximum spread from desired exposure before rebalancing triggers
     * @dev Gets the current tolerance for exposure deviation
     * @return The maximum deviation from desired exposure in basis points
     */
    function desiredExposureMaximalBpsSpread() external view returns (uint256);
    /**
     * @notice Updates the fee charged when minting IOU tokens
     * @dev Sets the fee percentage taken from IOU minting operations
     * @param _lpFee New LP fee in basis points (10000 = 100%)
     * @param _treasuryFee New treasury fee in basis points (10000 = 100%)
     */
    function setIouFeeBps(
        uint256 _lpFee,
        uint256 _treasuryFee        
    ) external;

    /**
     * @notice Returns the current IOU minting fee
     * @dev Gets the fee percentage charged when minting IOU tokens
     * @return lpFee The current lp fee in basis points
     * @return treasuryFee The current treasury fee in basis points
     */
    function iouFeeBps() external view returns (uint256 lpFee, uint256 treasuryFee);

    /**
     * @notice Checks if the vault's token exposures are within the desired balance range
     * @dev Iterates through all allowed tokens and verifies their exposure is within maximal spread from desired exposure
     * @return true if all token exposures are balanced within the acceptable range, false otherwise
     */
    function isBalanced() external view returns (bool);
    /**
     * @notice Returns the IOU token address for a given underlying token
     * @dev Gets the corresponding IOU token contract address
     * @param _token The underlying token address
     * @return The IOU token contract address
     */
    function iouOf(address _token) external returns (address);
    /**
     * @notice Returns the Curve pool address for a token's IOU trading
     * @dev Gets the Curve liquidity pool for token/IOU swaps
     * @param _token The underlying token address
     * @return The Curve pool contract address
     */
    function iouCurveMetaPoolOf(address _token) external view returns (address);
    
    /**
     * @notice Returns comprehensive vault configuration and token information
     * @dev Aggregates vault settings, fees, and detailed information about all enabled tokens
     *      Provides a complete view of vault state for external consumers
     * @return iouTreasuryFeeBps The current IOU minting treasury fee in basis points
     * @return iouLpFeeBps The current IOU minting LP fee in basis points
     * @return maximumRebalanceBpsSpread Maximum allowed slippage during rebalancing in basis points
     * @return desiredExposureMaximalBpsSpread Maximum deviation from desired exposure before rebalancing
     * @return totalAssets Total value of all assets managed by the vault
     * @return tokens Array of detailed information for all vault tokens including balances and configurations
     */
    function details() external view returns (
        uint256 iouTreasuryFeeBps,
        uint256 iouLpFeeBps,
        uint256 maximumRebalanceBpsSpread,
        uint256 desiredExposureMaximalBpsSpread,
        uint256 totalAssets,
        TokenDetails[] memory tokens
    );

    /**
     * @notice Executes a liquidity swap between tokens with optional IOU minting
     * @dev Performs token swap and optionally mints IOU tokens when liquidity is insufficient
     *      Validates exposure limits and charges fees on IOU minting
     * @param _receiver Address to receive the output tokens and IOUs
     * @param _from Input token address
     * @param _to Output token address
     * @param _amountIn Amount of input tokens
     * @param _amountOut Amount of output tokens to transfer
     * @param _amountIou Amount of IOU tokens to mint (if any)
     * @return iousReceived Actual IOU tokens received after fees
     */
    function swapLiquidity(
        address _receiver,
        address _from, 
        address _to, 
        uint256 _amountIn,
        uint256 _amountOut,
        uint256 _amountIou
    ) external returns (
        uint256 iousReceived
    );

    /**
     * @notice Redeems IOU tokens for underlying tokens
     * @dev Burns IOU tokens and transfers underlying tokens to receiver
     *      Updates emitted IOU tracking
     * @param _sender Address holding the IOU tokens to burn
     * @param _receiver Address to receive the underlying tokens
     * @param _token The underlying token address
     * @param _amount Amount of IOU tokens to redeem
     */
    function redeemIOU(
        address _sender,
        address _receiver,
        address _token,
        uint256 _amount
    ) external;

    /**
     * @notice Executes a rebalancing operation between two tokens
     * @dev Performs token swap using external contracts to rebalance vault exposure
     *      Validates slippage against maximum spread
     * @param _from Token to sell
     * @param _to Token to buy
     * @param _approval Contract to approve for token spending
     * @param _target Contract to execute the swap
     * @param _amount Amount of tokens to swap
     * @param _payload Encoded call data for the swap operation
     */
    function rebalance(
        address _from,
        address _to,
        address _approval, 
        address _target, 
        uint256 _amount, 
        bytes calldata _payload
    ) external;



    /**
     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function tokens() external view returns (address[] memory assets);

    /**
     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
     *
     * - SHOULD include any compounding that occurs from yield.
     * - MUST be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT revert.
     */
    function totalAssets() external view returns (uint256 totalManagedAssets);

    /**
     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToShares(address token, uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToAssets(address token, uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     *
     * - MUST return a limited value if receiver is subject to some deposit limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
     * - MUST NOT revert.
     */
    function maxDeposit(address token, address receiver) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
     *   in the same transaction.
     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewDeposit(address token, uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   deposit execution, and are accounted for during deposit.
     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function deposit(address token, uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
     * - MUST return a limited value if receiver is subject to some mint limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
     * - MUST NOT revert.
     */
    function maxMint(address token, address receiver) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
     *   same transaction.
     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
     *   would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by minting.
     */
    function previewMint(address token, uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
     *   execution, and are accounted for during mint.
     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function mint(address token, uint256 shares, address receiver) external returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxWithdraw(address token, address owner) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
     *   called
     *   in the same transaction.
     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewWithdraw(address token, uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   withdraw execution, and are accounted for during withdraw.
     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function withdraw(address token, uint256 assets, address receiver, address owner) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
     * through a redeem call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxRedeem(address token, address owner) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
     *   same transaction.
     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
     *   redemption would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
     */
    function previewRedeem(address token, uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   redeem execution, and are accounted for during redeem.
     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function redeem(address token, uint256 shares, address receiver, address owner) external returns (uint256 assets);


    
}

project/contracts/interfaces/external/ICurveStableSwapFactory.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;


interface ICurveStableSwapFactory {

    function deploy_plain_pool(
        string memory name,
        string memory symbol,
        address[] memory coins,
        uint256 A,
        uint256 fee,
        uint256 offpeg_fee_multiplier,
        uint256 ma_exp_time,
        uint256 implementation_idx,
        uint8[] memory asset_types,
        bytes4[] memory method_ids,
        address[] memory oracles
    ) external returns (address);

    function deploy_metapool(
        address base_pool,
        string memory name,
        string memory symbol,
        address coin,
        uint256 A,
        uint256 fee,
        uint256 offpeg_fee_multiplier,
        uint256 ma_exp_time,
        uint256 implementation_idx,
        uint8 asset_types,
        bytes4 method_ids,
        address oracles
    ) external returns (address);
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/",
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/",
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/",
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/",
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/",
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/",
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/",
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.