Skip to content
Verified contractExactMIT

WadzVaultFactory

Address0xf4ab3514cb05dd280ae10237d46bdfe5efc2b2d1
Balance

0 ETH

 

Transactions

90

 

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
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,633,543
Creation transaction
0x96bb440e22…c4f4f886d6

27 files

contracts/platform/factory/WadzVaultFactory.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

import { AccessControlDefaultAdminRules } from "@openzeppelin/contracts/access/extensions/AccessControlDefaultAdminRules.sol";
import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";

import { IWadzVaultFactory, SingleAssetSyncConfig, DualAssetConcLiqConfig } from "./IWadzVaultFactory.sol";
import { IWadzActionAuthorizer } from "../authorizer/IWadzActionAuthorizer.sol";
import { IWadzRewardsVault } from "../rewards/IWadzRewardsVault.sol";
import { ISingleAssetVaultDeployer } from "./ISingleAssetVaultDeployer.sol";
import { IDualAssetVaultDeployer } from "./IDualAssetVaultDeployer.sol";
import { IVaultRegistry, VaultRecord } from "../registry/IVaultRegistry.sol";
import { IWadzVaultCore } from "../../vaults/shared/IWadzVaultCore.sol";
import { IGenericERC4626Adapter } from "../../vaults/single-asset-sync/adapters/erc4626/IGenericERC4626Adapter.sol";
import { ISASWVault } from "../../vaults/single-asset-sync/ISASWVault.sol";
import { IDualAssetConcLiqVault } from "../../vaults/dual-asset-conc-liq/IDualAssetConcLiqVault.sol";
import { IDualAssetLpVaultAdapter } from "../../vaults/dual-asset-conc-liq/adapters/lp-vault/IDualAssetLpVaultAdapter.sol";
import { VaultKind } from "../types/WadzTypes.sol";

/// @title WadzVaultFactory
/// @notice Governance-controlled factory that deploys, wires, and registers WADZ vaults.
///         Supports both `SINGLE_ASSET_SYNC` (ERC4626 wrapper + adapter) and
///         `DUAL_ASSET_CONCENTRATED_LIQUIDITY` (dual-asset wrapper + LP vault adapter).
///         For each vault it calls the configured external deployer to create fresh
///         per-vault instances, verifies their bidirectional wiring, and registers
///         the vault in `VaultRegistry`.
/// @dev    Provider allowlist: the audited adapter type is fixed and deployed by
///         kind-specific deployers, so there is no `adapterImpl` to allowlist;
///         governance allowlists the `provider` vault per kind instead.
///
///         Single-asset wiring sequence (via external deployer): the factory calls
///         `ISingleAssetVaultDeployer(singleDeployer).deployAndWire(...)`, receives
///         the pair of addresses, then performs all post-deploy assertions (vault
///         kind and bidirectional wiring) and `registry.register(...)`.
///
///         Dual-asset wiring sequence (via external deployer): the factory delegates
///         the heavy `new DualAssetConcLiqWrapper` + `new DualAssetLpVaultAdapter` +
///         `wrapper.setAdapter(adapter)` sequence to `DualAssetVaultDeployer` (held
///         as `dualDeployer`), which carries the initcode in its own bytecode rather
///         than in the factory's. The factory calls `IDualAssetVaultDeployer(dualDeployer)
///         .deployAndWire(...)`, receives the pair of addresses, then performs all
///         post-deploy assertions (vault kind, bidirectional wiring, token ordering)
///         and `registry.register(...)`. The factory MUST NOT deploy a new
///         kind-specific deployer via `new` itself — that would re-embed initcode.
///         Instead deployer addresses are immutables set at construction.
///
///         Authorizer caller-registration (`authorizer.setCaller(wrapper, vaultId, true)`) is
///         performed atomically by the factory after registry registration. Governance
///         must grant this factory `CALLER_REGISTRAR_ROLE` on `WadzActionAuthorizer`
///         before deploying vaults; otherwise the deployment reverts and no wrapper
///         is registered. The factory must also be granted the registry's
///         vault-registration authority role (`registry.grantRole(
///         VAULT_REGISTRATION_AUTHORITY_ROLE, factory)`) by governance before deploying.
///
///         Access model: `AccessControlDefaultAdminRules` with a
///         `VAULT_DEPLOYER_ROLE` gating vault deployment. `DEFAULT_ADMIN_ROLE`
///         manages provider allowlists, the treasury used for future vaults, and
///         role grants. The role-bearing deployer does not become wrapper
///         governance; wrappers receive the separate immutable `vaultGovernance`
///         address. Updating the factory treasury does not migrate existing
///         wrappers; those use their own governance-gated `setTreasury`. The
///         mutable treasury allows a later migration to a rewards/claim contract
///         without redeploying the factory.
///
///         Upgradeability decision: NON-UPGRADEABLE (constructor + AccessControl).
///         The factory is admin infra holding only an allowlist and a vault counter;
///         deployed vaults do not reference it, so replacing the factory (and
///         re-granting the registry vault-registration role) does not affect
///         live vaults. No proxy justified.
contract WadzVaultFactory is IWadzVaultFactory, AccessControlDefaultAdminRules {
    // ─── Roles ───────────────────────────────────────────────────────────

    /// @notice Role permitted to deploy and register new WADZ vaults.
    bytes32 public constant VAULT_DEPLOYER_ROLE = keccak256("VAULT_DEPLOYER_ROLE");

    // ─── Immutables ──────────────────────────────────────────────────────

    /// @notice USDC accounting asset forwarded to every wrapper.
    address public immutable accountingAsset;

    /// @notice EIP-712 authorizer forwarded to every wrapper.
    address public immutable authorizer;

    /// @notice Registry every deployed vault is recorded in.
    IVaultRegistry public immutable registry;

    /// @notice Governance forwarded to every wrapper deployed by this factory.
    address public immutable vaultGovernance;

    /// @notice External deployer that holds the single-asset wrapper + adapter
    ///         initcode. Calling `deployAndWire` on this contract keeps creation
    ///         bytecode out of the factory.
    address public immutable singleDeployer;

    /// @notice External deployer that holds the dual-asset wrapper + adapter
    ///         initcode. Calling `deployAndWire` on this contract keeps the heavy
    ///         creation bytecode out of the factory's own runtime bytecode, ensuring
    ///         the factory stays under the 24 KB EIP-170 limit.
    address public immutable dualDeployer;

    // ─── Storage ─────────────────────────────────────────────────────────

    /// @notice Treasury forwarded to newly deployed wrappers for protocol/emergency routing.
    address public override treasury;

    /// @dev Allowlisted providers by vault kind.
    mapping(VaultKind kind => mapping(address provider => bool)) private _providerAllowed;

    /// @dev Monotonic vault id counter; ids start at 1.
    uint256 private _nextVaultId;

    // ─── Constructor ─────────────────────────────────────────────────────

    /// @param _initialAdminTransferDelay Timelock delay (seconds) enforced on future
    ///                         default-admin transfers (`beginDefaultAdminTransfer`
    ///                         → wait → accept).
    /// @param _admin           Factory default admin; manages roles and allowlists.
    /// @param _vaultGovernance Governance address forwarded to deployed wrappers.
    /// @param _accountingAsset USDC accounting asset.
    /// @param _authorizer      EIP-712 action authorizer.
    /// @param _registry        Vault registry (governance must set this factory as
    ///                         its registration authority).
    /// @param _treasury        Protocol/treasury destination.
    /// @param _singleDeployer  External `SingleAssetVaultDeployer` that holds single-asset
    ///                         wrapper + adapter initcode. Must not be address(0).
    /// @param _dualDeployer    External `DualAssetVaultDeployer` that holds dual-asset
    ///                         wrapper + adapter initcode. Must not be address(0).
    constructor(
        uint48 _initialAdminTransferDelay,
        address _admin,
        address _vaultGovernance,
        address _accountingAsset,
        address _authorizer,
        address _registry,
        address _treasury,
        address _singleDeployer,
        address _dualDeployer
    ) AccessControlDefaultAdminRules(_initialAdminTransferDelay, _admin) {
        if (
            _vaultGovernance == address(0) ||
            _accountingAsset == address(0) ||
            _authorizer == address(0) ||
            _registry == address(0) ||
            _treasury == address(0) ||
            _singleDeployer == address(0) ||
            _dualDeployer == address(0)
        ) {
            revert ZeroAddress();
        }
        vaultGovernance = _vaultGovernance;
        accountingAsset = _accountingAsset;
        authorizer = _authorizer;
        registry = IVaultRegistry(_registry);
        treasury = _treasury;
        singleDeployer = _singleDeployer;
        dualDeployer = _dualDeployer;
        _grantRole(VAULT_DEPLOYER_ROLE, _admin);
    }

    // ─── Admin ───────────────────────────────────────────────────────────

    /// @inheritdoc IWadzVaultFactory
    function setProviderAllowed(
        VaultKind _kind,
        address _provider,
        bool _allowed
    ) external override onlyRole(DEFAULT_ADMIN_ROLE) {
        if (_provider == address(0)) revert ZeroAddress();
        _providerAllowed[_kind][_provider] = _allowed;
        emit ProviderAllowlistUpdated(_kind, _provider, _allowed);
    }

    /// @inheritdoc IWadzVaultFactory
    function setTreasury(address _treasury) external override onlyRole(DEFAULT_ADMIN_ROLE) {
        if (_treasury == address(0)) revert ZeroAddress();
        address previousTreasury = treasury;
        treasury = _treasury;
        emit TreasurySet(previousTreasury, _treasury);
    }

    // ─── Deployment ──────────────────────────────────────────────────────

    /// @inheritdoc IWadzVaultFactory
    function deploySingleAssetSyncVault(
        SingleAssetSyncConfig calldata _cfg
    ) external override onlyRole(VAULT_DEPLOYER_ROLE) returns (uint256 vaultId, address wrapper, address adapter) {
        if (_cfg.provider == address(0) || _cfg.depositAsset == address(0)) revert ZeroAddress();
        if (!_providerAllowed[VaultKind.SINGLE_ASSET_SYNC][_cfg.provider]) {
            revert ProviderNotAllowed(VaultKind.SINGLE_ASSET_SYNC, _cfg.provider);
        }
        // Oracle presence rule mirrors the wrapper's own guard, surfaced earlier.
        if ((_cfg.depositAsset == accountingAsset) != (_cfg.oracle == address(0))) revert OracleConfigMismatch();
        // The provider's underlying asset must equal the deposit asset.
        address providerAsset = IERC4626(_cfg.provider).asset();
        if (providerAsset != _cfg.depositAsset) revert AssetMismatch(providerAsset, _cfg.depositAsset);

        vaultId = ++_nextVaultId;

        (wrapper, adapter) = _deploySingleAssetSyncPair(vaultId, _cfg);

        // Assert the pair is wired correctly and is the expected kind.
        if (IWadzVaultCore(wrapper).vaultKind() != VaultKind.SINGLE_ASSET_SYNC) revert VaultKindMismatch();
        if (IGenericERC4626Adapter(adapter).wrapper() != wrapper || ISASWVault(wrapper).adapter() != adapter) {
            revert WiringMismatch();
        }

        registry.register(
            vaultId,
            VaultRecord({
                vaultKind: VaultKind.SINGLE_ASSET_SYNC,
                wrapper: wrapper,
                adapter: adapter,
                accountingAsset: accountingAsset,
                oracle: _cfg.oracle,
                riskBadge: _cfg.riskBadge,
                metadataHash: _cfg.metadataHash,
                visible: true
            })
        );
        IWadzActionAuthorizer(authorizer).setCaller(wrapper, vaultId, true);
        // Register the wrapper on the rewards vault (the treasury) so it can `credit`
        // protocol/referral entitlements during signed claims/withdraws. Requires the
        // factory to hold WRAPPER_REGISTRAR_ROLE on the RewardsVault (granted at setup);
        // the treasury is always a WadzRewardsVault in this deployment model.
        IWadzRewardsVault(treasury).setWrapper(wrapper, true);

        emit VaultDeployed(vaultId, VaultKind.SINGLE_ASSET_SYNC, wrapper, adapter, _cfg.oracle);
    }

    /// @inheritdoc IWadzVaultFactory
    function deployDualAssetConcLiqVault(
        DualAssetConcLiqConfig calldata _cfg
    ) external override onlyRole(VAULT_DEPLOYER_ROLE) returns (uint256 vaultId, address wrapper, address adapter) {
        // ── Validations ──────────────────────────────────────────────────────
        if (
            _cfg.provider == address(0) ||
            _cfg.token0 == address(0) ||
            _cfg.token1 == address(0) ||
            _cfg.oracle == address(0)
        ) {
            revert ZeroAddress();
        }
        if (_cfg.token0 == _cfg.token1) revert AssetMismatch(_cfg.token0, _cfg.token1);
        if (!_providerAllowed[VaultKind.DUAL_ASSET_CONCENTRATED_LIQUIDITY][_cfg.provider]) {
            revert ProviderNotAllowed(VaultKind.DUAL_ASSET_CONCENTRATED_LIQUIDITY, _cfg.provider);
        }

        vaultId = ++_nextVaultId;

        // ── Deploy + wire via external deployer ───────────────────────────────
        // The dual-asset wrapper and adapter initcodes live in `DualAssetVaultDeployer`
        // (not in this contract). The deployer atomically deploys the wrapper, deploys
        // the adapter, and calls `wrapper.setAdapter(adapter)` — it is authorized
        // because it is the wrapper's `_deployer` (msg.sender at wrapper construction).
        (wrapper, adapter) = IDualAssetVaultDeployer(dualDeployer).deployAndWire(
            accountingAsset,
            vaultId,
            authorizer,
            treasury,
            vaultGovernance,
            _cfg.token0,
            _cfg.token1,
            _cfg.oracle,
            _cfg.provider
        );

        // ── Assert: vault kind ───────────────────────────────────────────────
        if (IWadzVaultCore(wrapper).vaultKind() != VaultKind.DUAL_ASSET_CONCENTRATED_LIQUIDITY) {
            revert VaultKindMismatch();
        }

        // ── Assert: bidirectional wiring ─────────────────────────────────────
        if (
            IDualAssetLpVaultAdapter(adapter).wrapper() != wrapper ||
            IDualAssetConcLiqVault(wrapper).adapter() != adapter
        ) {
            revert WiringMismatch();
        }

        // ── Assert: token ordering matches the provider's actual wants() ──────
        // The adapter derived token0/token1 from `VaultConcLiq.wants()` in its
        // constructor. This cross-checks the config's declared pair against the live
        // provider ordering; reverts if they differ.
        address adapterToken0 = IDualAssetLpVaultAdapter(adapter).token0();
        address adapterToken1 = IDualAssetLpVaultAdapter(adapter).token1();
        if (adapterToken0 != _cfg.token0) revert AssetMismatch(adapterToken0, _cfg.token0);
        if (adapterToken1 != _cfg.token1) revert AssetMismatch(adapterToken1, _cfg.token1);

        // ── Assert: fee instrumentation ───────────────────────────────────────
        // Guard that the adapter exposes feeIndexes() (i.e. the strategy is the
        // WADZ-instrumented one that publishes cumulativeFeePerShare). A VaultConcLiq
        // backed by a non-instrumented strategy would deploy and register here
        // successfully but brick every deposit/withdraw at the feeIndexes() selector.
        try IDualAssetLpVaultAdapter(adapter).feeIndexes() {} catch {
            revert ProviderNotInstrumented();
        }

        // ── Register ──────────────────────────────────────────────────────────
        registry.register(
            vaultId,
            VaultRecord({
                vaultKind: VaultKind.DUAL_ASSET_CONCENTRATED_LIQUIDITY,
                wrapper: wrapper,
                adapter: adapter,
                accountingAsset: accountingAsset,
                oracle: _cfg.oracle,
                riskBadge: _cfg.riskBadge,
                metadataHash: _cfg.metadataHash,
                visible: true
            })
        );
        IWadzActionAuthorizer(authorizer).setCaller(wrapper, vaultId, true);
        // Register the wrapper on the rewards vault (the treasury) so it can `credit`
        // protocol/referral entitlements during signed claims/withdraws. Requires the
        // factory to hold WRAPPER_REGISTRAR_ROLE on the RewardsVault (granted at setup);
        // the treasury is always a WadzRewardsVault in this deployment model.
        IWadzRewardsVault(treasury).setWrapper(wrapper, true);

        emit VaultDeployed(vaultId, VaultKind.DUAL_ASSET_CONCENTRATED_LIQUIDITY, wrapper, adapter, _cfg.oracle);
    }

    // ─── Internals ───────────────────────────────────────────────────────

    /// @dev Deploy and atomically wire a single-asset wrapper/adapter pair through
    ///      the external single-asset deployer.
    /// @param _vaultId Registry id assigned by this factory before deployment.
    /// @param _cfg     Single-asset vault configuration supplied to the public entrypoint.
    /// @return wrapper Deployed `SASWVault` address.
    /// @return adapter Deployed `GenericERC4626Adapter` address.
    function _deploySingleAssetSyncPair(
        uint256 _vaultId,
        SingleAssetSyncConfig calldata _cfg
    ) private returns (address wrapper, address adapter) {
        // Deploy + wire via external deployer. The factory only receives the
        // resulting pair and performs post-deploy assertions before registration.
        return
            ISingleAssetVaultDeployer(singleDeployer).deployAndWire(
                accountingAsset,
                _vaultId,
                authorizer,
                treasury,
                vaultGovernance,
                _cfg.depositAsset,
                _cfg.oracle,
                _cfg.provider
            );
    }

    // ─── Views ───────────────────────────────────────────────────────────

    /// @inheritdoc IWadzVaultFactory
    function isProviderAllowed(VaultKind _kind, address _provider) external view override returns (bool) {
        return _providerAllowed[_kind][_provider];
    }
}

@openzeppelin/contracts/access/AccessControl.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (access/AccessControl.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    mapping(bytes32 role => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /// @inheritdoc ERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        return _roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        if (!hasRole(role, account)) {
            _roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        if (hasRole(role, account)) {
            _roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

@openzeppelin/contracts/access/IAccessControl.sol

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

pragma solidity >=0.8.4;

/**
 * @dev External interface of AccessControl declared to support ERC-165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted to signal this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}

@openzeppelin/contracts/access/extensions/AccessControlDefaultAdminRules.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (access/extensions/AccessControlDefaultAdminRules.sol)

pragma solidity ^0.8.20;

import {IAccessControlDefaultAdminRules} from "./IAccessControlDefaultAdminRules.sol";
import {AccessControl, IAccessControl} from "../AccessControl.sol";
import {SafeCast} from "../../utils/math/SafeCast.sol";
import {Math} from "../../utils/math/Math.sol";
import {IERC5313} from "../../interfaces/IERC5313.sol";
import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Extension of {AccessControl} that allows specifying special rules to manage
 * the `DEFAULT_ADMIN_ROLE` holder, which is a sensitive role with special permissions
 * over other roles that may potentially have privileged rights in the system.
 *
 * If a specific role doesn't have an admin role assigned, the holder of the
 * `DEFAULT_ADMIN_ROLE` will have the ability to grant it and revoke it.
 *
 * This contract implements the following risk mitigations on top of {AccessControl}:
 *
 * * Only one account holds the `DEFAULT_ADMIN_ROLE` since deployment until it's potentially renounced.
 * * Enforces a 2-step process to transfer the `DEFAULT_ADMIN_ROLE` to another account.
 * * Enforces a configurable delay between the two steps, with the ability to cancel before the transfer is accepted.
 * * The delay can be changed by scheduling, see {changeDefaultAdminDelay}.
 * * Role transfers must wait at least one block after scheduling before it can be accepted.
 * * It is not possible to use another role to manage the `DEFAULT_ADMIN_ROLE`.
 *
 * Example usage:
 *
 * ```solidity
 * contract MyToken is AccessControlDefaultAdminRules {
 *   constructor() AccessControlDefaultAdminRules(
 *     3 days,
 *     msg.sender // Explicit initial `DEFAULT_ADMIN_ROLE` holder
 *    ) {}
 * }
 * ```
 */
abstract contract AccessControlDefaultAdminRules is IAccessControlDefaultAdminRules, IERC5313, AccessControl {
    // pending admin pair read/written together frequently
    address private _pendingDefaultAdmin;
    uint48 private _pendingDefaultAdminSchedule; // 0 == unset

    uint48 private _currentDelay;
    address private _currentDefaultAdmin;

    // pending delay pair read/written together frequently
    uint48 private _pendingDelay;
    uint48 private _pendingDelaySchedule; // 0 == unset

    /**
     * @dev Sets the initial values for {defaultAdminDelay} and {defaultAdmin} address.
     */
    constructor(uint48 initialDelay, address initialDefaultAdmin) {
        if (initialDefaultAdmin == address(0)) {
            revert AccessControlInvalidDefaultAdmin(address(0));
        }
        _currentDelay = initialDelay;
        _grantRole(DEFAULT_ADMIN_ROLE, initialDefaultAdmin);
    }

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControlDefaultAdminRules).interfaceId || super.supportsInterface(interfaceId);
    }

    /// @inheritdoc IERC5313
    function owner() public view virtual returns (address) {
        return defaultAdmin();
    }

    ///
    /// Override AccessControl role management
    ///

    /**
     * @dev See {AccessControl-grantRole}. Reverts for `DEFAULT_ADMIN_ROLE`.
     */
    function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
        if (role == DEFAULT_ADMIN_ROLE) {
            revert AccessControlEnforcedDefaultAdminRules();
        }
        super.grantRole(role, account);
    }

    /**
     * @dev See {AccessControl-revokeRole}. Reverts for `DEFAULT_ADMIN_ROLE`.
     */
    function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
        if (role == DEFAULT_ADMIN_ROLE) {
            revert AccessControlEnforcedDefaultAdminRules();
        }
        super.revokeRole(role, account);
    }

    /**
     * @dev See {AccessControl-renounceRole}.
     *
     * For the `DEFAULT_ADMIN_ROLE`, it only allows renouncing in two steps by first calling
     * {beginDefaultAdminTransfer} to the `address(0)`, so it's required that the {pendingDefaultAdmin} schedule
     * has also passed when calling this function.
     *
     * After its execution, it will not be possible to call `onlyRole(DEFAULT_ADMIN_ROLE)` functions.
     *
     * NOTE: Renouncing `DEFAULT_ADMIN_ROLE` will leave the contract without a {defaultAdmin},
     * thereby disabling any functionality that is only available for it, and the possibility of reassigning a
     * non-administrated role.
     */
    function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
        if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) {
            (address newDefaultAdmin, uint48 schedule) = pendingDefaultAdmin();
            if (newDefaultAdmin != address(0) || !_isScheduleSet(schedule) || !_hasSchedulePassed(schedule)) {
                revert AccessControlEnforcedDefaultAdminDelay(schedule);
            }
            delete _pendingDefaultAdminSchedule;
        }
        super.renounceRole(role, account);
    }

    /**
     * @dev See {AccessControl-_grantRole}.
     *
     * For `DEFAULT_ADMIN_ROLE`, it only allows granting if there isn't already a {defaultAdmin} or if the
     * role has been previously renounced.
     *
     * NOTE: Exposing this function through another mechanism may make the `DEFAULT_ADMIN_ROLE`
     * assignable again. Make sure to guarantee this is the expected behavior in your implementation.
     */
    function _grantRole(bytes32 role, address account) internal virtual override returns (bool) {
        if (role == DEFAULT_ADMIN_ROLE) {
            if (defaultAdmin() != address(0)) {
                revert AccessControlEnforcedDefaultAdminRules();
            }
            _currentDefaultAdmin = account;
        }
        return super._grantRole(role, account);
    }

    /// @inheritdoc AccessControl
    function _revokeRole(bytes32 role, address account) internal virtual override returns (bool) {
        if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) {
            delete _currentDefaultAdmin;
        }
        return super._revokeRole(role, account);
    }

    /**
     * @dev See {AccessControl-_setRoleAdmin}. Reverts for `DEFAULT_ADMIN_ROLE`.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual override {
        if (role == DEFAULT_ADMIN_ROLE) {
            revert AccessControlEnforcedDefaultAdminRules();
        }
        super._setRoleAdmin(role, adminRole);
    }

    ///
    /// AccessControlDefaultAdminRules accessors
    ///

    /// @inheritdoc IAccessControlDefaultAdminRules
    function defaultAdmin() public view virtual returns (address) {
        return _currentDefaultAdmin;
    }

    /// @inheritdoc IAccessControlDefaultAdminRules
    function pendingDefaultAdmin() public view virtual returns (address newAdmin, uint48 schedule) {
        return (_pendingDefaultAdmin, _pendingDefaultAdminSchedule);
    }

    /// @inheritdoc IAccessControlDefaultAdminRules
    function defaultAdminDelay() public view virtual returns (uint48) {
        uint48 schedule = _pendingDelaySchedule;
        return (_isScheduleSet(schedule) && _hasSchedulePassed(schedule)) ? _pendingDelay : _currentDelay;
    }

    /// @inheritdoc IAccessControlDefaultAdminRules
    function pendingDefaultAdminDelay() public view virtual returns (uint48 newDelay, uint48 schedule) {
        schedule = _pendingDelaySchedule;
        return (_isScheduleSet(schedule) && !_hasSchedulePassed(schedule)) ? (_pendingDelay, schedule) : (0, 0);
    }

    /// @inheritdoc IAccessControlDefaultAdminRules
    function defaultAdminDelayIncreaseWait() public view virtual returns (uint48) {
        return 5 days;
    }

    ///
    /// AccessControlDefaultAdminRules public and internal setters for defaultAdmin/pendingDefaultAdmin
    ///

    /// @inheritdoc IAccessControlDefaultAdminRules
    function beginDefaultAdminTransfer(address newAdmin) public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
        _beginDefaultAdminTransfer(newAdmin);
    }

    /**
     * @dev See {beginDefaultAdminTransfer}.
     *
     * Internal function without access restriction.
     */
    function _beginDefaultAdminTransfer(address newAdmin) internal virtual {
        uint48 newSchedule = SafeCast.toUint48(block.timestamp) + defaultAdminDelay();
        _setPendingDefaultAdmin(newAdmin, newSchedule);
        emit DefaultAdminTransferScheduled(newAdmin, newSchedule);
    }

    /// @inheritdoc IAccessControlDefaultAdminRules
    function cancelDefaultAdminTransfer() public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
        _cancelDefaultAdminTransfer();
    }

    /**
     * @dev See {cancelDefaultAdminTransfer}.
     *
     * Internal function without access restriction.
     */
    function _cancelDefaultAdminTransfer() internal virtual {
        _setPendingDefaultAdmin(address(0), 0);
    }

    /// @inheritdoc IAccessControlDefaultAdminRules
    function acceptDefaultAdminTransfer() public virtual {
        (address newDefaultAdmin, ) = pendingDefaultAdmin();
        if (_msgSender() != newDefaultAdmin) {
            // Enforce newDefaultAdmin explicit acceptance.
            revert AccessControlInvalidDefaultAdmin(_msgSender());
        }
        _acceptDefaultAdminTransfer();
    }

    /**
     * @dev See {acceptDefaultAdminTransfer}.
     *
     * Internal function without access restriction.
     */
    function _acceptDefaultAdminTransfer() internal virtual {
        (address newAdmin, uint48 schedule) = pendingDefaultAdmin();
        if (!_isScheduleSet(schedule) || !_hasSchedulePassed(schedule)) {
            revert AccessControlEnforcedDefaultAdminDelay(schedule);
        }
        _revokeRole(DEFAULT_ADMIN_ROLE, defaultAdmin());
        _grantRole(DEFAULT_ADMIN_ROLE, newAdmin);
        delete _pendingDefaultAdmin;
        delete _pendingDefaultAdminSchedule;
    }

    ///
    /// AccessControlDefaultAdminRules public and internal setters for defaultAdminDelay/pendingDefaultAdminDelay
    ///

    /// @inheritdoc IAccessControlDefaultAdminRules
    function changeDefaultAdminDelay(uint48 newDelay) public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
        _changeDefaultAdminDelay(newDelay);
    }

    /**
     * @dev See {changeDefaultAdminDelay}.
     *
     * Internal function without access restriction.
     */
    function _changeDefaultAdminDelay(uint48 newDelay) internal virtual {
        uint48 newSchedule = SafeCast.toUint48(block.timestamp) + _delayChangeWait(newDelay);
        _setPendingDelay(newDelay, newSchedule);
        emit DefaultAdminDelayChangeScheduled(newDelay, newSchedule);
    }

    /// @inheritdoc IAccessControlDefaultAdminRules
    function rollbackDefaultAdminDelay() public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
        _rollbackDefaultAdminDelay();
    }

    /**
     * @dev See {rollbackDefaultAdminDelay}.
     *
     * Internal function without access restriction.
     */
    function _rollbackDefaultAdminDelay() internal virtual {
        _setPendingDelay(0, 0);
    }

    /**
     * @dev Returns the amount of seconds to wait after the `newDelay` will
     * become the new {defaultAdminDelay}.
     *
     * The value returned guarantees that if the delay is reduced, it will go into effect
     * after a wait that honors the previously set delay.
     *
     * See {defaultAdminDelayIncreaseWait}.
     */
    function _delayChangeWait(uint48 newDelay) internal view virtual returns (uint48) {
        uint48 currentDelay = defaultAdminDelay();

        // When increasing the delay, we schedule the delay change to occur after a period of "new delay" has passed, up
        // to a maximum given by defaultAdminDelayIncreaseWait, by default 5 days. For example, if increasing from 1 day
        // to 3 days, the new delay will come into effect after 3 days. If increasing from 1 day to 10 days, the new
        // delay will come into effect after 5 days. The 5 day wait period is intended to be able to fix an error like
        // using milliseconds instead of seconds.
        //
        // When decreasing the delay, we wait the difference between "current delay" and "new delay". This guarantees
        // that an admin transfer cannot be made faster than "current delay" at the time the delay change is scheduled.
        // For example, if decreasing from 10 days to 3 days, the new delay will come into effect after 7 days.
        return
            newDelay > currentDelay
                ? uint48(Math.min(newDelay, defaultAdminDelayIncreaseWait())) // no need to safecast, both inputs are uint48
                : currentDelay - newDelay;
    }

    ///
    /// Private setters
    ///

    /**
     * @dev Setter of the tuple for pending admin and its schedule.
     *
     * May emit a {DefaultAdminTransferCanceled} event.
     */
    function _setPendingDefaultAdmin(address newAdmin, uint48 newSchedule) private {
        (, uint48 oldSchedule) = pendingDefaultAdmin();

        _pendingDefaultAdmin = newAdmin;
        _pendingDefaultAdminSchedule = newSchedule;

        // An `oldSchedule` from `pendingDefaultAdmin()` is only set if it hasn't been accepted.
        if (_isScheduleSet(oldSchedule)) {
            // Emit for implicit cancellations when another default admin was scheduled.
            emit DefaultAdminTransferCanceled();
        }
    }

    /**
     * @dev Setter of the tuple for pending delay and its schedule.
     *
     * May emit a {DefaultAdminDelayChangeCanceled} event.
     */
    function _setPendingDelay(uint48 newDelay, uint48 newSchedule) private {
        uint48 oldSchedule = _pendingDelaySchedule;

        if (_isScheduleSet(oldSchedule)) {
            if (_hasSchedulePassed(oldSchedule)) {
                // Materialize a virtual delay
                _currentDelay = _pendingDelay;
            } else {
                // Emit for implicit cancellations when another delay was scheduled.
                emit DefaultAdminDelayChangeCanceled();
            }
        }

        _pendingDelay = newDelay;
        _pendingDelaySchedule = newSchedule;
    }

    ///
    /// Private helpers
    ///

    /**
     * @dev Defines if a `schedule` is considered set. For consistency purposes.
     */
    function _isScheduleSet(uint48 schedule) private pure returns (bool) {
        return schedule != 0;
    }

    /**
     * @dev Defines if a `schedule` is considered passed. For consistency purposes.
     */
    function _hasSchedulePassed(uint48 schedule) private view returns (bool) {
        return schedule < block.timestamp;
    }
}

@openzeppelin/contracts/access/extensions/IAccessControlDefaultAdminRules.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (access/extensions/IAccessControlDefaultAdminRules.sol)

pragma solidity >=0.8.4;

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

/**
 * @dev External interface of AccessControlDefaultAdminRules declared to support ERC-165 detection.
 */
interface IAccessControlDefaultAdminRules is IAccessControl {
    /**
     * @dev The new default admin is not a valid default admin.
     */
    error AccessControlInvalidDefaultAdmin(address defaultAdmin);

    /**
     * @dev At least one of the following rules was violated:
     *
     * - The `DEFAULT_ADMIN_ROLE` must only be managed by itself.
     * - The `DEFAULT_ADMIN_ROLE` must only be held by one account at the time.
     * - Any `DEFAULT_ADMIN_ROLE` transfer must be in two delayed steps.
     */
    error AccessControlEnforcedDefaultAdminRules();

    /**
     * @dev The delay for transferring the default admin delay is enforced and
     * the operation must wait until `schedule`.
     *
     * NOTE: `schedule` can be 0 indicating there's no transfer scheduled.
     */
    error AccessControlEnforcedDefaultAdminDelay(uint48 schedule);

    /**
     * @dev Emitted when a {defaultAdmin} transfer is started, setting `newAdmin` as the next
     * address to become the {defaultAdmin} by calling {acceptDefaultAdminTransfer} only after `acceptSchedule`
     * passes.
     */
    event DefaultAdminTransferScheduled(address indexed newAdmin, uint48 acceptSchedule);

    /**
     * @dev Emitted when a {pendingDefaultAdmin} is reset if it was never accepted, regardless of its schedule.
     */
    event DefaultAdminTransferCanceled();

    /**
     * @dev Emitted when a {defaultAdminDelay} change is started, setting `newDelay` as the next
     * delay to be applied between default admin transfer after `effectSchedule` has passed.
     */
    event DefaultAdminDelayChangeScheduled(uint48 newDelay, uint48 effectSchedule);

    /**
     * @dev Emitted when a {pendingDefaultAdminDelay} is reset if its schedule didn't pass.
     */
    event DefaultAdminDelayChangeCanceled();

    /**
     * @dev Returns the address of the current `DEFAULT_ADMIN_ROLE` holder.
     */
    function defaultAdmin() external view returns (address);

    /**
     * @dev Returns a tuple of a `newAdmin` and an accept schedule.
     *
     * After the `schedule` passes, the `newAdmin` will be able to accept the {defaultAdmin} role
     * by calling {acceptDefaultAdminTransfer}, completing the role transfer.
     *
     * A zero value only in `acceptSchedule` indicates no pending admin transfer.
     *
     * NOTE: A zero address `newAdmin` means that {defaultAdmin} is being renounced.
     */
    function pendingDefaultAdmin() external view returns (address newAdmin, uint48 acceptSchedule);

    /**
     * @dev Returns the delay required to schedule the acceptance of a {defaultAdmin} transfer started.
     *
     * This delay will be added to the current timestamp when calling {beginDefaultAdminTransfer} to set
     * the acceptance schedule.
     *
     * NOTE: If a delay change has been scheduled, it will take effect as soon as the schedule passes, making this
     * function returns the new delay. See {changeDefaultAdminDelay}.
     */
    function defaultAdminDelay() external view returns (uint48);

    /**
     * @dev Returns a tuple of `newDelay` and an effect schedule.
     *
     * After the `schedule` passes, the `newDelay` will get into effect immediately for every
     * new {defaultAdmin} transfer started with {beginDefaultAdminTransfer}.
     *
     * A zero value only in `effectSchedule` indicates no pending delay change.
     *
     * NOTE: A zero value only for `newDelay` means that the next {defaultAdminDelay}
     * will be zero after the effect schedule.
     */
    function pendingDefaultAdminDelay() external view returns (uint48 newDelay, uint48 effectSchedule);

    /**
     * @dev Starts a {defaultAdmin} transfer by setting a {pendingDefaultAdmin} scheduled for acceptance
     * after the current timestamp plus a {defaultAdminDelay}.
     *
     * Requirements:
     *
     * - Only can be called by the current {defaultAdmin}.
     *
     * Emits a {DefaultAdminTransferScheduled} event.
     */
    function beginDefaultAdminTransfer(address newAdmin) external;

    /**
     * @dev Cancels a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}.
     *
     * A {pendingDefaultAdmin} not yet accepted can also be cancelled with this function.
     *
     * Requirements:
     *
     * - Only can be called by the current {defaultAdmin}.
     *
     * May emit a {DefaultAdminTransferCanceled} event.
     */
    function cancelDefaultAdminTransfer() external;

    /**
     * @dev Completes a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}.
     *
     * After calling the function:
     *
     * - `DEFAULT_ADMIN_ROLE` should be granted to the caller.
     * - `DEFAULT_ADMIN_ROLE` should be revoked from the previous holder.
     * - {pendingDefaultAdmin} should be reset to zero values.
     *
     * Requirements:
     *
     * - Only can be called by the {pendingDefaultAdmin}'s `newAdmin`.
     * - The {pendingDefaultAdmin}'s `acceptSchedule` should've passed.
     */
    function acceptDefaultAdminTransfer() external;

    /**
     * @dev Initiates a {defaultAdminDelay} update by setting a {pendingDefaultAdminDelay} scheduled for getting
     * into effect after the current timestamp plus a {defaultAdminDelay}.
     *
     * This function guarantees that any call to {beginDefaultAdminTransfer} done between the timestamp this
     * method is called and the {pendingDefaultAdminDelay} effect schedule will use the current {defaultAdminDelay}
     * set before calling.
     *
     * The {pendingDefaultAdminDelay}'s effect schedule is defined in a way that waiting until the schedule and then
     * calling {beginDefaultAdminTransfer} with the new delay will take at least the same as another {defaultAdmin}
     * complete transfer (including acceptance).
     *
     * The schedule is designed for two scenarios:
     *
     * - When the delay is changed for a larger one the schedule is `block.timestamp + newDelay` capped by
     * {defaultAdminDelayIncreaseWait}.
     * - When the delay is changed for a shorter one, the schedule is `block.timestamp + (current delay - new delay)`.
     *
     * A {pendingDefaultAdminDelay} that never got into effect will be canceled in favor of a new scheduled change.
     *
     * Requirements:
     *
     * - Only can be called by the current {defaultAdmin}.
     *
     * Emits a {DefaultAdminDelayChangeScheduled} event and may emit a {DefaultAdminDelayChangeCanceled} event.
     */
    function changeDefaultAdminDelay(uint48 newDelay) external;

    /**
     * @dev Cancels a scheduled {defaultAdminDelay} change.
     *
     * Requirements:
     *
     * - Only can be called by the current {defaultAdmin}.
     *
     * May emit a {DefaultAdminDelayChangeCanceled} event.
     */
    function rollbackDefaultAdminDelay() external;

    /**
     * @dev Maximum time in seconds for an increase to {defaultAdminDelay} (that is scheduled using {changeDefaultAdminDelay})
     * to take effect. Default to 5 days.
     *
     * When the {defaultAdminDelay} is scheduled to be increased, it goes into effect after the new delay has passed with
     * the purpose of giving enough time for reverting any accidental change (i.e. using milliseconds instead of seconds)
     * that may lock the contract. However, to avoid excessive schedules, the wait is capped by this function and it can
     * be overridden for a custom {defaultAdminDelay} increase scheduling.
     *
     * IMPORTANT: Make sure to add a reasonable amount of time while overriding this value, otherwise,
     * there's a risk of setting a high new delay that goes into effect almost immediately without the
     * possibility of human intervention in the case of an input error (eg. set milliseconds instead of seconds).
     */
    function defaultAdminDelayIncreaseWait() external view returns (uint48);
}

@openzeppelin/contracts/interfaces/IERC4626.sol

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

pragma solidity >=0.6.2;

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

/**
 * @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 */
interface IERC4626 is IERC20, IERC20Metadata {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);

    event Withdraw(
        address indexed sender,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /**
     * @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 asset() external view returns (address assetTokenAddress);

    /**
     * @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(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(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 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(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Deposit `assets` underlying tokens and send the corresponding number of vault shares (`shares`) to `receiver`.
     *
     * - 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(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 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(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Mints exactly `shares` vault shares to `receiver` in exchange for `assets` 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(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 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(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(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 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(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(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}

@openzeppelin/contracts/interfaces/IERC5313.sol

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

pragma solidity >=0.4.16;

/**
 * @dev Interface for the Light Contract Ownership Standard.
 *
 * A standardized minimal interface required to identify an account that controls a contract
 */
interface IERC5313 {
    /**
     * @dev Gets the address of the owner.
     */
    function owner() external view returns (address);
}

@openzeppelin/contracts/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);
}

@openzeppelin/contracts/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);
}

@openzeppelin/contracts/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;
    }
}

@openzeppelin/contracts/utils/Panic.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

@openzeppelin/contracts/utils/introspection/ERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

@openzeppelin/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

@openzeppelin/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `condition ? a : b`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `condition ? a : b`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // (a + b) / 2 can overflow.
            return (a & b) + (a ^ b) / 2;
        }
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory buffer) private pure returns (bool) {
        uint256 chunk;
        for (uint256 i = 0; i < buffer.length; i += 0x20) {
            // See _unsafeReadBytesOffset from utils/Bytes.sol
            assembly ("memory-safe") {
                chunk := mload(add(add(buffer, 0x20), i))
            }
            if (chunk >> (8 * saturatingSub(i + 0x20, buffer.length)) != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the first 16 bytes (most significant half).
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }

    /**
     * @dev Counts the number of leading zero bits in a uint256.
     */
    function clz(uint256 x) internal pure returns (uint256) {
        return ternary(x == 0, 256, 255 - log2(x));
    }
}

@openzeppelin/contracts/utils/math/SafeCast.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in a uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in a uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev A uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

contracts/platform/authorizer/IWadzActionAuthorizer.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

// ─── Enums ───────────────────────────────────────────────────────────

/// @notice Normal user actions that require a backend EIP-712 authorization.
/// @dev    `emergencyRedeem` is intentionally absent: it is signature-free and
///         must remain callable without backend authorization.
enum WadzActionType {
    Deposit,
    Claim,
    Withdraw
}

// ─── Structs ─────────────────────────────────────────────────────────

/// @notice Canonical signed-action payload. Mirrors the EIP-712 typed-data the
///         backend signs to authorize a single normal operation.
/// @dev    `chainId` and `verifyingContract` are NOT fields here: they are bound
///         by the EIP-712 domain separator inside the authorizer, so replay
///         across chains or verifier contracts is rejected at signature recovery.
///         `userAmount`/`protocolAmount` are the exact signed routing the wrapper
///         must execute on claim/withdraw; the wrapper never invents the split.
///         Units of `amount`/`userAmount`/`protocolAmount` are the wrapper's
///         transfer token (depositAsset for SINGLE_ASSET_SYNC).
struct SignedAction {
    // Action being authorized: Deposit, Claim, or Withdraw.
    WadzActionType action;
    // Wallet that must execute the tx (the wrapper enforces msg.sender == user).
    address user;
    // Target vault id (binds the signature to one vault).
    uint256 vaultId;
    // Off-chain license reference (policy lives in the backend).
    uint256 licenseId;
    // Target position id; 0 when opening a new position (deposit).
    uint256 positionId;
    // Action-specific magnitude. For a dual-asset Deposit this is
    // uint256(keccak256(abi.encode(amount0, amount1))); for other actions it keeps
    // the wrapper-defined unit (for example provider shares on a dual withdraw).
    uint256 amount;
    // Portion of `amount` routed to the user (signed split; 0 on deposit).
    uint256 userAmount;
    // Portion of `amount` routed to treasury (signed split; 0 on deposit).
    uint256 protocolAmount;
    // keccak256 commitment to the off-chain breakdown of `protocolAmount` into
    // per-recipient, per-token entitlements credited in the rewards/treasury
    // contract (referrers + protocol). `bytes32(0)` means "no breakdown": the
    // action carries no split and `protocolAmount` is routed to treasury as a
    // lump (deposits and non-referral claims/withdraws). The wrapper only records
    // a breakdown when this is non-zero and it matches the provided calldata.
    bytes32 protocolSplitHash;
    // L1 referrer for attribution, or address(0) if none.
    address referrer;
    // Unix timestamp after which the signature is no longer valid.
    uint256 deadline;
    // Single-use nonce per user (anti-replay).
    uint256 nonce;
}

/// @title IWadzActionAuthorizer
/// @notice Boundary for the EIP-712 verifier that authorizes normal wrapper
///         operations on behalf of the WADZ backend.
/// @dev    Wrappers call `verifyAndConsume` and then bind the call to the signed
///         payload (msg.sender == user, vaultId, action) themselves.
interface IWadzActionAuthorizer {
    // ─── Errors ──────────────────────────────────────────────────────────

    /// @notice Recovered signer is not an authorized backend signer.
    error UnauthorizedSigner(address signer);

    /// @notice Signed deadline has passed.
    error SignatureExpired(uint256 deadline);

    /// @notice Nonce has already been consumed for this user.
    error NonceAlreadyUsed(address user, uint256 nonce);

    // ─── Events ──────────────────────────────────────────────────────────

    /// @notice Emitted after a signed action is verified and its nonce consumed.
    event ActionAuthorized(address indexed user, WadzActionType indexed action, uint256 indexed vaultId, uint256 nonce);

    // ─── Functions ─────────────────────────────────────────────────────────

    /// @notice Authorize or revoke a backend signer.
    /// @dev Callable only by `SIGNER_ADMIN_ROLE` on the concrete authorizer.
    function setSigner(address _signer, bool _authorized) external;

    /// @notice Authorize or revoke a wrapper caller for a vault id.
    /// @dev Callable only by `CALLER_REGISTRAR_ROLE` on the concrete authorizer.
    function setCaller(address _caller, uint256 _vaultId, bool _authorized) external;

    /// @notice Verify a signed action and consume its nonce in the same call.
    /// @dev    Reverts unless: the caller is an authorized caller (the verifier may
    ///         restrict this to governance-registered WADZ wrappers); the recovered
    ///         signer is authorized; the EIP-712 signature is valid for the exact
    ///         typed data (domain binds `block.chainid` and this contract as
    ///         `verifyingContract`); the deadline has not expired; and the nonce was
    ///         unused. Consumes the nonce on success. Does NOT check `msg.sender ==
    ///         user`: the calling wrapper binds that.
    /// @param _action    The signed action payload.
    /// @param _signature The backend signature over `_action`.
    function verifyAndConsume(SignedAction calldata _action, bytes calldata _signature) external;

    // ─── Views ───────────────────────────────────────────────────────────

    /// @notice Returns true if `_signer` is an authorized backend signer.
    function isAuthorizedSigner(address _signer) external view returns (bool);

    /// @notice Returns true if `_nonce` has already been consumed for `_user`.
    function isNonceUsed(address _user, uint256 _nonce) external view returns (bool);

    /// @notice Role permitted to authorize or revoke backend EIP-712 signers.
    function SIGNER_ADMIN_ROLE() external view returns (bytes32);

    /// @notice Role permitted to authorize or revoke wrapper callers.
    function CALLER_REGISTRAR_ROLE() external view returns (bytes32);

    /// @notice Returns true if `_caller` may call `verifyAndConsume`.
    function isAuthorizedCaller(address _caller) external view returns (bool);

    /// @notice Returns the vault id `_caller` is authorized to serve (0 = unauthorized).
    function callerVaultId(address _caller) external view returns (uint256);

    /// @notice Returns the domain-separated EIP-712 digest for `_action` — the value
    ///         the backend signs and that `verifyAndConsume` recovers against
    ///         (for off-chain signing/testing).
    function hashAction(SignedAction calldata _action) external view returns (bytes32);
}

contracts/platform/factory/IDualAssetVaultDeployer.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

/// @title IDualAssetVaultDeployer
/// @notice Stateless helper that deploys and atomically wires a
///         `DualAssetConcLiqWrapper` + `DualAssetLpVaultAdapter` pair.
///         Exists solely to keep the heavy wrapper/adapter initcode OUT of the
///         `WadzVaultFactory` runtime bytecode (which would exceed the 24 KB
///         EIP-170 limit if the factory held it directly via `new`).
/// @dev    The deployer is stateless and permissionless: anyone can call
///         `deployAndWire`, but the result is an UNREGISTERED orphan unless a
///         registry-authorized caller (i.e. the factory) subsequently calls
///         `VaultRegistry.register`. The factory is the intended and only
///         meaningful caller, but the contract does not enforce this — doing so
///         would require passing the factory address in and would couple the
///         deployer to a specific factory instance, preventing reuse if the
///         factory is replaced.
///
///         Because the deployer deploys the wrapper via `new DualAssetConcLiqWrapper(...)`,
///         it becomes the wrapper's `_deployer` immutable and is therefore
///         authorized to call `wrapper.setAdapter(adapter)` once. This is
///         the deployer-gated wiring pattern (`NotDeployer` guard) — the call
///         is made atomically inside `deployAndWire` with no front-run window.
///
///         Upgradeability decision: NON-UPGRADEABLE. The deployer is a stateless
///         deploy helper with no storage, no configuration, and no owner. Its
///         only role is to emit creation bytecode for wrapper + adapter and wire
///         them. Replacement is simply re-deploying a new instance; the factory
///         points to it via its own immutable `dualDeployer` (updating that
///         requires replacing the factory). No proxy justified.
interface IDualAssetVaultDeployer {
    // ─── Errors ──────────────────────────────────────────────────────────

    /// @notice A zero address was supplied where a real address is required.
    error ZeroAddress();

    // ─── Functions ───────────────────────────────────────────────────────

    /// @notice Deploy a fresh `DualAssetConcLiqWrapper` + `DualAssetLpVaultAdapter`
    ///         pair, wire them atomically, and return both addresses.
    /// @dev    Deploy order: wrapper first (no adapter address at construction) →
    ///         adapter (requires wrapper address; reads `wants()` from `_provider`) →
    ///         `wrapper.setAdapter(adapter)` (deployer-gated; this contract is the
    ///         wrapper's `_deployer`). All three steps occur in the same call.
    ///         The returned wrapper and adapter are wired but NOT registered.
    ///         Caller (the factory) is responsible for all post-deploy assertions
    ///         and `VaultRegistry.register(...)`.
    ///         Reverts `ZeroAddress` if any address argument is the zero address.
    /// @param _accountingAsset USDC accounting asset forwarded to the wrapper.
    /// @param _vaultId         Registry key forwarded to the wrapper.
    /// @param _authorizer      EIP-712 authorizer forwarded to the wrapper.
    /// @param _treasury        Treasury address forwarded to the wrapper.
    /// @param _governance      Governance address forwarded to the wrapper.
    /// @param _token0          First token of the LP pair.
    /// @param _token1          Second token of the LP pair.
    /// @param _oracle          Dual-asset valuation oracle; must be non-zero.
    /// @param _provider        VaultConcLiq provider vault; adapter reads `wants()` from it.
    /// @return wrapper         Deployed and wired `DualAssetConcLiqWrapper` address.
    /// @return adapter         Deployed `DualAssetLpVaultAdapter` address, wired to wrapper.
    function deployAndWire(
        address _accountingAsset,
        uint256 _vaultId,
        address _authorizer,
        address _treasury,
        address _governance,
        address _token0,
        address _token1,
        address _oracle,
        address _provider
    ) external returns (address wrapper, address adapter);
}

contracts/platform/factory/ISingleAssetVaultDeployer.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

/// @title ISingleAssetVaultDeployer
/// @notice Stateless helper that deploys and atomically wires a `SASWVault` +
///         `GenericERC4626Adapter` pair.
/// @dev    The deployer is stateless and permissionless: anyone can call
///         `deployAndWire`, but the result is an UNREGISTERED orphan unless a
///         registry-authorized caller (i.e. the factory) subsequently calls
///         `VaultRegistry.register`. The factory is the intended and only
///         meaningful caller, but the contract does not enforce this to keep the
///         deployer reusable across factory replacements.
///
///         Because the deployer deploys the adapter via `new GenericERC4626Adapter(...)`,
///         it becomes the adapter's `_deployer` immutable and is therefore
///         authorized to call `adapter.initialize(wrapper)` once. This resolves the
///         wrapper↔adapter circular reference atomically inside `deployAndWire`.
///
///         Upgradeability decision: NON-UPGRADEABLE. The deployer is a stateless
///         deploy helper with no storage, no configuration, and no owner. Its only
///         role is to emit creation bytecode for wrapper + adapter and wire them.
///         Replacement is simply re-deploying a new instance; the factory points
///         to it via its own immutable `singleDeployer`. No proxy justified.
interface ISingleAssetVaultDeployer {
    // ─── Errors ──────────────────────────────────────────────────────────

    /// @notice A zero address was supplied where a real address is required.
    error ZeroAddress();

    // ─── Functions ───────────────────────────────────────────────────────

    /// @notice Deploy a fresh `SASWVault` + `GenericERC4626Adapter` pair, wire
    ///         them atomically, and return both addresses.
    /// @dev    Deploy order: adapter first (sets this contract as adapter deployer)
    ///         → wrapper(adapter) → `adapter.initialize(wrapper)` (deployer-gated).
    ///         The returned wrapper and adapter are wired but NOT registered.
    ///         Caller (the factory) is responsible for all post-deploy assertions
    ///         and `VaultRegistry.register(...)`.
    ///         Reverts `ZeroAddress` if a required address argument is zero.
    /// @param _accountingAsset       USDC accounting asset forwarded to the wrapper.
    /// @param _vaultId               Registry key forwarded to the wrapper.
    /// @param _authorizer            EIP-712 authorizer forwarded to the wrapper.
    /// @param _treasury              Treasury address forwarded to the wrapper.
    /// @param _governance            Governance address forwarded to the wrapper.
    /// @param _depositAsset          Single asset accepted by the wrapper.
    /// @param _oracle                Valuation oracle, or address(0) for USDC.
    /// @param _provider              ERC4626 provider vault.
    /// @return wrapper               Deployed and wired `SASWVault` address.
    /// @return adapter               Deployed `GenericERC4626Adapter` address, wired to wrapper.
    function deployAndWire(
        address _accountingAsset,
        uint256 _vaultId,
        address _authorizer,
        address _treasury,
        address _governance,
        address _depositAsset,
        address _oracle,
        address _provider
    ) external returns (address wrapper, address adapter);
}

contracts/platform/factory/IWadzVaultFactory.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

import { VaultKind } from "../types/WadzTypes.sol";

// ─── Structs ─────────────────────────────────────────────────────────

/// @notice Deploy configuration for a SINGLE_ASSET_SYNC vault.
/// @dev    No `adapterImpl` field: the audited adapter type is fixed
///         (`GenericERC4626Adapter`, deployed fresh per vault), so the on-chain
///         allowlist vets the `provider` ERC4626 vault instead. `oracle` must be
///         address(0) iff `depositAsset` is the USDC accounting asset (trivial path).
struct SingleAssetSyncConfig {
    address provider; // ERC4626 provider vault (also its share token)
    address depositAsset; // single asset accepted at deposit (USDC / USDS / USDe)
    address oracle; // IValuationOracle; address(0) iff depositAsset == USDC
    string riskBadge; // UI risk label
    bytes32 metadataHash; // off-chain metadata pointer
}

/// @notice Deploy configuration for a DUAL_ASSET_CONCENTRATED_LIQUIDITY vault.
/// @dev    `token0`/`token1` declare the expected LP pair ordering. The factory
///         validates them against the provider's actual `wants()` ordering (read from
///         the deployed adapter) and reverts `AssetMismatch` on any mismatch.
///         `oracle` must be non-zero: dual-asset vaults always require valuation; there
///         is no trivial-USDC path equivalent to single-asset. `riskBadge` and
///         `metadataHash` are registry metadata, not validated on-chain.
struct DualAssetConcLiqConfig {
    address provider; // VaultConcLiq provider vault (also the ERC-20 share token)
    address token0; // expected first token of the LP pair (must match provider's wants()[0])
    address token1; // expected second token of the LP pair (must match provider's wants()[1])
    address oracle; // IValuationOracle for dual-asset USDC valuation; must be non-zero
    string riskBadge; // UI risk label
    bytes32 metadataHash; // off-chain metadata pointer
}

/// @title IWadzVaultFactory
/// @notice Governance-controlled factory that deploys and registers WADZ vaults of
///         multiple vault kinds (single-asset-sync, dual-asset-conc-liq). Only
///         allowlisted providers can back a new vault.
/// @dev    Calls kind-specific external deployers to deploy and wire a fresh
///         per-vault adapter instance and wrapper, registers the vault in
///         `VaultRegistry`, and authorizes the wrapper as an authorizer caller.
///         Governance must grant the factory the authorizer's caller-registrar role
///         before deployments.
///
///         Single and dual wiring sequences both use external deployers. The factory
///         delegates deploy+wire to the deployer immutable for the vault kind,
///         receives the wired pair of addresses, then performs all post-deploy
///         assertions and `registry.register(...)`. The deployers hold wrapper and
///         adapter initcodes so the factory does not embed creation bytecode.
///
///         `DEFAULT_ADMIN_ROLE` manages provider allowlists, treasury updates, and
///         role grants; `VAULT_DEPLOYER_ROLE` gates vault deployment.
///         `vaultGovernance` is forwarded to wrappers independently from the
///         caller that deploys. Factory treasury updates only affect vaults
///         deployed after the update; existing wrappers expose their own
///         governance-gated `setTreasury`.
interface IWadzVaultFactory {
    // ─── Errors ──────────────────────────────────────────────────────────

    /// @notice The provider is not allowlisted for the given vault kind.
    error ProviderNotAllowed(VaultKind kind, address provider);

    /// @notice A zero address was supplied where a real address is required.
    error ZeroAddress();

    /// @notice depositAsset/oracle configuration is inconsistent (USDC must have no
    ///         oracle; a non-USDC asset must have one).
    error OracleConfigMismatch();

    /// @notice The provider's underlying asset does not match `depositAsset`.
    error AssetMismatch(address providerAsset, address depositAsset);

    /// @notice A deployed wrapper reported an unexpected vault kind.
    error VaultKindMismatch();

    /// @notice The deployed adapter and wrapper are not wired to each other.
    error WiringMismatch();

    /// @notice The deployed dual-asset adapter does not expose `feeIndexes()`.
    ///         Only adapters backed by the WADZ-instrumented strategy (which publishes
    ///         `cumulativeFeePerShare` indexes) are safe to register. An adapter without
    ///         `feeIndexes()` would brick every deposit and withdrawal at the fee-index
    ///         selector after registration.
    error ProviderNotInstrumented();

    // ─── Events ──────────────────────────────────────────────────────────

    /// @notice Emitted when a provider is allowlisted or revoked for a kind.
    event ProviderAllowlistUpdated(VaultKind indexed kind, address indexed provider, bool allowed);

    /// @notice Emitted when the factory treasury destination for future vaults changes.
    /// @param previousTreasury Previous treasury forwarded to new vaults.
    /// @param newTreasury New treasury forwarded to new vaults.
    event TreasurySet(address indexed previousTreasury, address indexed newTreasury);

    /// @notice Emitted when a new vault is deployed and registered.
    event VaultDeployed(
        uint256 indexed vaultId,
        VaultKind indexed kind,
        address indexed wrapper,
        address adapter,
        address oracle
    );

    // ─── Functions ─────────────────────────────────────────────────────────

    /// @notice Allowlist or revoke a provider vault for a vault kind.
    /// @dev Callable only by `DEFAULT_ADMIN_ROLE`.
    function setProviderAllowed(VaultKind _kind, address _provider, bool _allowed) external;

    /// @notice Change the treasury destination forwarded to future vault deployments.
    /// @dev Callable only by `DEFAULT_ADMIN_ROLE`. Does not update existing wrappers;
    ///      migrate those through each wrapper's governance-gated `setTreasury`.
    /// @param _treasury New treasury forwarded to future vault deployments.
    function setTreasury(address _treasury) external;

    /// @notice Deploy and register a SINGLE_ASSET_SYNC vault (adapter + wrapper).
    /// @dev Callable only by `VAULT_DEPLOYER_ROLE`.
    /// @return vaultId Registry key.
    /// @return wrapper Deployed wrapper address.
    /// @return adapter Deployed per-vault adapter instance address.
    function deploySingleAssetSyncVault(
        SingleAssetSyncConfig calldata _cfg
    ) external returns (uint256 vaultId, address wrapper, address adapter);

    /// @notice Deploy and register a DUAL_ASSET_CONCENTRATED_LIQUIDITY vault
    ///         (adapter + wrapper). Callable only by `VAULT_DEPLOYER_ROLE`.
    ///         Wiring sequence: external deployer deploys
    ///         wrapper → deploys adapter → `wrapper.setAdapter(adapter)`
    ///         (deployer-gated) → factory asserts pairing and token ordering →
    ///         `registry.register(...)`.
    /// @dev    `_cfg.oracle` must be non-zero (dual vaults always require valuation).
    ///         `_cfg.token0`/`_cfg.token1` must match the ordering returned by
    ///         `VaultConcLiq.wants()` as read from the deployed adapter; any mismatch
    ///         reverts `AssetMismatch`. `_cfg.provider` must be allowlisted for
    ///         `DUAL_ASSET_CONCENTRATED_LIQUIDITY`; reverts `ProviderNotAllowed` if not.
    ///         Reverts `ZeroAddress` if `provider`, `token0`, `token1`, or `oracle` is zero.
    ///         Reverts `VaultKindMismatch` if the wrapper reports an unexpected kind.
    ///         Reverts `WiringMismatch` if adapter↔wrapper bidirectional references are wrong.
    /// @return vaultId Registry key.
    /// @return wrapper Deployed dual-asset wrapper address.
    /// @return adapter Deployed dual-asset adapter instance address.
    function deployDualAssetConcLiqVault(
        DualAssetConcLiqConfig calldata _cfg
    ) external returns (uint256 vaultId, address wrapper, address adapter);

    // ─── Views ───────────────────────────────────────────────────────────

    /// @notice Returns true if `_provider` is allowlisted for `_kind`.
    function isProviderAllowed(VaultKind _kind, address _provider) external view returns (bool);

    /// @notice Role permitted to deploy and register new WADZ vaults.
    function VAULT_DEPLOYER_ROLE() external view returns (bytes32);

    /// @notice Governance address forwarded to every wrapper deployed by this factory.
    function vaultGovernance() external view returns (address);

    /// @notice Treasury destination forwarded to vaults deployed after the latest update.
    function treasury() external view returns (address);

    /// @notice The `SingleAssetVaultDeployer` that holds the single-asset wrapper and
    ///         adapter initcodes. Immutable after deployment.
    function singleDeployer() external view returns (address);

    /// @notice The `DualAssetVaultDeployer` that holds the dual-asset wrapper and
    ///         adapter initcodes. Immutable after deployment.
    function dualDeployer() external view returns (address);
}

contracts/platform/registry/IVaultRegistry.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

import { VaultKind } from "../types/WadzTypes.sol";

// ─── Structs ─────────────────────────────────────────────────────────

/// @notice Catalog record for a deployed WADZ vault.
/// @dev    Append-only: every field except `visible` is fixed at registration.
///         `accountingAsset` is always USDC in the MVP; `oracle` is address(0) for
///         the trivial-USDC valuation path.
struct VaultRecord {
    VaultKind vaultKind;
    address wrapper;
    address adapter;
    address accountingAsset;
    address oracle;
    string riskBadge;
    bytes32 metadataHash;
    bool visible;
}

/// @title IVaultRegistry
/// @notice Catalog of all deployed WADZ vault wrappers. Written by the factory
///         (registration) and governance (visibility); read by the frontend and
///         platform tooling.
/// @dev    Records are append-only; the only mutable field post-registration is
///         `visible`.
interface IVaultRegistry {
    // ─── Errors ──────────────────────────────────────────────────────────

    /// @notice Caller is not permitted to register vaults.
    error NotVaultRegistrationAuthority(address caller);

    /// @notice A zero address was supplied where a real address is required.
    error ZeroAddress();

    /// @notice A vault with this id is already registered (records are append-only).
    error VaultAlreadyRegistered(uint256 vaultId);

    /// @notice No vault is registered under this id.
    error UnknownVault(uint256 vaultId);

    // ─── Events ──────────────────────────────────────────────────────────

    /// @notice Emitted when a new vault is registered.
    event VaultRegistered(uint256 indexed vaultId, address indexed wrapper, VaultKind kind);

    /// @notice Emitted when a vault's UI visibility is toggled.
    event VaultVisibilityChanged(uint256 indexed vaultId, bool visible);

    // ─── Functions ─────────────────────────────────────────────────────────

    /// @notice Register a new vault. Callable only by accounts holding the
    ///         vault-registration-authority role (the factories).
    /// @dev    Reverts on duplicate `_vaultId` or zero wrapper/accountingAsset.
    function register(uint256 _vaultId, VaultRecord calldata _record) external;

    /// @notice Toggle a vault's UI visibility. Does not affect functionality.
    ///         Restricted to the default admin (governance).
    function setVisible(uint256 _vaultId, bool _visible) external;

    // ─── Views ───────────────────────────────────────────────────────────

    /// @notice Returns the record for `_vaultId`. Reverts if it does not exist.
    function getVault(uint256 _vaultId) external view returns (VaultRecord memory);

    /// @notice Returns true if `_vaultId` is registered.
    function isRegistered(uint256 _vaultId) external view returns (bool);

    /// @notice Returns all registered vault ids.
    function allVaultIds() external view returns (uint256[] memory);

    /// @notice Returns all registered vault ids of a given kind.
    function vaultIdsByKind(VaultKind _kind) external view returns (uint256[] memory);
}

contracts/platform/rewards/IWadzRewardsVault.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

// ─── Structs ─────────────────────────────────────────────────────────

/// @notice One share of a wrapper's protocol cut: `bps` (out of 10_000) of a given
///         `token`, owed to `recipient`.
/// @dev    Shares are PERCENTAGES, not absolute amounts, so a single breakdown works
///         for both single-asset (one token, exact amount known) and dual-asset (the
///         protocol cut is a proportional slice of BOTH tokens whose exact per-token
///         amounts are only known at redeem time). Per token, the `bps` of all entries
///         must sum to 10_000. The abi-encoding of a `ProtocolSplitShare[]` is what the
///         backend commits to via `SignedAction.protocolSplitHash`.
struct ProtocolSplitShare {
    // Referrer or protocol address entitled to the share.
    address recipient;
    // Token the share applies to (in-kind; no swaps).
    address token;
    // Share of that token's routed protocol amount, out of 10_000.
    uint16 bps;
}

/// @title IWadzRewardsVault
/// @notice Boundary for the WADZ rewards/treasury contract: a multi-token
///         pull-payment ledger that receives each vault's protocol cut and records
///         per-recipient (referrer + protocol) entitlements, which recipients later
///         claim WITHOUT a backend signature.
/// @dev    Wrappers call `credit` when routing a protocol cut; recipients call
///         `claim`. The split is decided off-chain by the backend and committed in
///         `SignedAction.protocolSplitHash`; all split validation lives in `credit`
///         (not in the wrappers) so every vault kind only has to forward.
interface IWadzRewardsVault {
    // ─── Errors ──────────────────────────────────────────────────────────

    /// @notice A zero address was supplied where a non-zero one is required.
    error ZeroAddress();

    /// @notice `credit` caller is not a registered WADZ wrapper.
    error NotAuthorizedWrapper(address caller);

    /// @notice The provided breakdown does not match the signed `splitHash`.
    error SplitHashMismatch();

    /// @notice The `bps` of the breakdown entries for a token do not sum to 10_000.
    error InvalidBpsSum(address token, uint256 bpsSum);

    /// @notice The vault does not hold enough of the token to back the credit.
    /// @dev    `required` = existing `totalOwed` + this credit; `available` = balance.
    error InsufficientBacking(address token, uint256 required, uint256 available);

    /// @notice The caller has no claimable balance for the token.
    error NothingToClaim(address recipient, address token);

    /// @notice A sweep tried to take more than the unassigned (non-credited) balance.
    error ExceedsUnassigned(uint256 requested, uint256 available);

    // ─── Events ──────────────────────────────────────────────────────────

    /// @notice Emitted when a wrapper is allowlisted or revoked as a `credit` caller.
    event WrapperSet(address indexed wrapper, bool allowed);

    /// @notice Emitted for each recipient credited by a `credit` call.
    /// @param recipient Address whose entitlement grew.
    /// @param token     Token credited.
    /// @param amount    Amount credited to `recipient` for `token`.
    /// @param splitHash Backend commitment the credit was validated against.
    event Credited(address indexed recipient, address indexed token, uint256 amount, bytes32 indexed splitHash);

    /// @notice Emitted when a recipient claims their entitlement for a token.
    event Claimed(address indexed recipient, address indexed token, uint256 amount);

    /// @notice Emitted when governance sweeps unassigned (non-credited) balance.
    event SweptUnassigned(address indexed token, address indexed to, uint256 amount);

    // ─── Wrapper registry (admin) ─────────────────────────────────────────

    /// @notice Allowlist or revoke a WADZ wrapper as an authorized `credit` caller.
    /// @dev    Gated by `WRAPPER_REGISTRAR_ROLE` (held by the factory for atomic
    ///         registration at vault deployment; governance retains it for repair).
    /// @param _wrapper Wrapper address.
    /// @param _allowed Whether it may call `credit`.
    function setWrapper(address _wrapper, bool _allowed) external;

    // ─── Credit (wrappers) ────────────────────────────────────────────────

    /// @notice Record entitlements for `amount` of `token` just routed by a wrapper,
    ///         split among recipients per the signed `breakdown`.
    /// @dev    Callable only by registered WADZ wrappers, which MUST have transferred
    ///         `amount` of `token` to this contract in the same transaction (so
    ///         recorded entitlements are always fully backed). Verifies
    ///         `keccak256(abi.encode(breakdown)) == splitHash` and that the `bps` of the
    ///         entries whose `token` matches sum to 10_000, then applies
    ///         `owed[recipient][token] += bps * amount / 10_000` to each (the last
    ///         matching entry absorbs the rounding remainder so credits sum exactly to
    ///         `amount`). A dual-asset wrapper calls this once per token with the same
    ///         `splitHash`/`breakdown`.
    /// @param _splitHash Backend commitment to `_breakdown` (from the signed action).
    /// @param _breakdown Per-recipient, per-token shares (bps).
    /// @param _token     Token being credited.
    /// @param _amount    Amount of `_token` routed for this action.
    function credit(
        bytes32 _splitHash,
        ProtocolSplitShare[] calldata _breakdown,
        address _token,
        uint256 _amount
    ) external;

    // ─── Claim (recipients) ───────────────────────────────────────────────

    /// @notice Claim the caller's full entitlement for a token, sent to the caller.
    /// @dev    Signature-free: entitlements were already authorized when credited.
    /// @param _token Token to claim.
    /// @return amount Amount transferred to the caller.
    function claim(address _token) external returns (uint256 amount);

    // ─── Views ────────────────────────────────────────────────────────────

    /// @notice Whether `_wrapper` may call `credit`.
    function isWrapper(address _wrapper) external view returns (bool);

    /// @notice Claimable balance of `_recipient` for `_token`.
    function owed(address _recipient, address _token) external view returns (uint256);

    /// @notice Total credited-but-unclaimed balance for `_token` (sum of all `owed`).
    /// @dev    The vault balance minus this is the unassigned amount governance may sweep.
    function totalOwed(address _token) external view returns (uint256);

    // ─── Sweep unassigned (admin) ─────────────────────────────────────────

    /// @notice Sweep unassigned (non-credited) balance of a token to `_to`.
    /// @dev    Gated by `DEFAULT_ADMIN_ROLE`. Can only move `balanceOf(this) - totalOwed`
    ///         — protocol revenue that arrived without a per-recipient split (emergency
    ///         surplus, dust, legacy lump). Credited entitlements are never touchable.
    /// @param _token  Token to sweep.
    /// @param _to     Destination (protocol treasury).
    /// @param _amount Amount to sweep (≤ unassigned balance).
    function sweep(address _token, address _to, uint256 _amount) external;
}

contracts/platform/types/WadzTypes.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

// ─── Enums ───────────────────────────────────────────────────────────

/// @notice Vault kind taxonomy. A new kind is required when deposit shape,
///         withdrawal lifecycle, valuation model, or emergency behavior differs.
/// @dev    `SINGLE_ASSET_ASYNC` is reserved for a future asynchronous withdrawal
///         lifecycle so the shared type encoding remains stable.
enum VaultKind {
    SINGLE_ASSET_SYNC, // generic ERC4626 wrapper
    DUAL_ASSET_CONCENTRATED_LIQUIDITY, // concentrated-liquidity LP wrapper
    SINGLE_ASSET_ASYNC // out of MVP scope; reserved
}

/// @notice Lifecycle state of a deployed vault instance.
/// @dev    Paused blocks new deposits; withdraw/claim/emergency remain available.
///         Deprecated blocks new deposits permanently; existing positions can exit.
enum VaultState {
    Active,
    Paused,
    Deprecated
}

/// @notice Lifecycle state of a single user position inside a wrapper.
/// @dev    WithdrawPending only applies to the async kind (out of MVP scope).
enum PositionStatus {
    Active,
    WithdrawPending,
    Closed,
    EmergencyClosed
}

// ─── Structs ─────────────────────────────────────────────────────────

/// @notice Canonical position record. Stored inside each wrapper, never in a
///         shared registry, because `receiptAmount` semantics are kind-specific
///         and only the wrapper can convert it to a USDC value.
/// @dev    For SINGLE_ASSET_SYNC, `receiptAmount` is the provider ERC4626 share
///         balance held by the wrapper. `principalUsdc` is fixed at deposit time
///         via the valuation oracle. `adapterMetadata` is empty for sync kinds.
///         Profit recognized through claims and partial withdrawals.
///         dev Does not include profit implicit in a full close. Reconstruct the
///         complete history off-chain from wrapper events and ERC-20 transfers.
struct Position {
    uint256 positionId;
    address owner;
    uint256 licenseId;
    uint256 vaultId;
    VaultKind vaultKind;
    uint256 receiptAmount;
    uint256 principalUsdc;
    uint256 claimedProfitUsdc;
    uint64 openedAt;
    PositionStatus status;
    bytes adapterMetadata;
}

contracts/vaults/dual-asset-conc-liq/IDualAssetConcLiqVault.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

import { IWadzVaultCore } from "../shared/IWadzVaultCore.sol";
import { SignedAction } from "../../platform/authorizer/IWadzActionAuthorizer.sol";
import { ProtocolSplitShare } from "../../platform/rewards/IWadzRewardsVault.sol";

/// @title IDualAssetConcLiqVault
/// @notice Vault-kind interface for DUAL_ASSET_CONCENTRATED_LIQUIDITY. Adds the
///         dual-token action surface to `IWadzVaultCore`. Backed by a
///         `DualAssetLpVaultAdapter` that proxies `VaultConcLiq` calls; the wrapper
///         custodies VaultConcLiq ERC-20 shares internally — users receive only a
///         non-transferable WADZ `positionId`, never the LP shares directly.
///
///         There is NO `claim()` on this interface (profit is recognized only at
///         withdrawal in MVP). There are NO single-asset deposit/withdraw/
///         emergencyRedeem overloads — only the dual-token forms below.
///
/// @dev    Policy checks are off-chain: the backend authorizes each action via
///         an EIP-712 `SignedAction`.
///         `licenseId`, `referrer`, `positionId`, and the `userAmount`/
///         `protocolAmount` routing split all arrive INSIDE the signed payload
///         and are bound by the wrapper AFTER `verifyAndConsume`.
///
///         Partial and full withdraws share one entrypoint: `_action.amount ==
///         type(uint256).max` means full close; any other value is the share count
///         to redeem. This eliminates a redundant ABI entry with identical
///         semantics.
///
///         `withdrawMany` is NOT present: the dual-asset routing model (in-kind,
///         two-token, proportional) makes aggregation non-trivial.
interface IDualAssetConcLiqVault is IWadzVaultCore {
    // ─── Errors ──────────────────────────────────────────────────────────

    /// @notice Deposit signed action had a non-zero `positionId` or non-zero split
    ///         fields (`userAmount`/`protocolAmount`). Deposit actions do not route
    ///         funds — the split is computed at withdrawal.
    error InvalidDepositAction();

    /// @notice Signed dual-deposit amount commitment does not match calldata amounts.
    /// @param signedCommitment Commitment supplied in `SignedAction.amount`.
    /// @param calldataCommitment Commitment derived from the actual `_amount0` and `_amount1`.
    error DepositAmountsMismatch(uint256 signedCommitment, uint256 calldataCommitment);

    /// @notice A withdraw with a protocol cut (`protocolAmount > 0`) carried no signed
    ///         split (`protocolSplitHash == 0`); every cut must be attributable.
    error MissingProtocolSplit();

    /// @notice Caller is not the owner of the target position.
    error NotPositionOwner(uint256 positionId, address caller);

    /// @notice Target position is not in the required `Active` status.
    error PositionNotActive(uint256 positionId);

    /// @notice Provided amount is zero where a positive amount is required.
    error ZeroAmount();

    /// @notice Deposit minted zero provider shares (e.g. dust amounts rounded down).
    error ZeroShares();

    /// @notice The signed `licenseId` does not match the position's stored license.
    ///         Licenses are fixed at deposit and cannot change for a position.
    error LicenseMismatch(uint256 provided, uint256 expected);

    /// @notice Signed routing is inconsistent: the USDC split does not cover the
    ///         redeemed value (totalValueUsdc < userAmount + protocolAmount).
    error InsufficientRedeemed(uint256 totalValueUsdc, uint256 owed);

    /// @notice The signed `protocolAmount` is non-zero but the withdrawn portion is
    ///         net-negative (current value <= recorded principal). Charging a fee on
    ///         a loss is forbidden.
    error FeeOnLoss();

    /// @notice The signed `protocolAmount` exceeds the fee-only attributable profit of
    ///         the withdrawn portion, capped by net gain.
    ///         `feeOnlyUsdc` = min(pendingFeeUsdc, netGainUsdc) for the withdrawn portion.
    error FeeExceedsFeeOnlyProfit(uint256 protocolAmount, uint256 feeOnlyUsdc);

    /// @notice Both `_minOut0` and `_minOut1` were zero on an emergency redeem.
    ///         At least one non-zero floor is required as an anti-sandwich guard.
    ///         A TWAP-based auto-floor may be added later.
    error ZeroMinOut();

    /// @notice The signed deposit committed a zero `minShares`, i.e. no dilution floor.
    error ZeroMinShares();

    /// @notice Normal operations (deposit/withdraw) require the pool to be calm.
    ///         Emergency redeem intentionally does NOT check this.
    error NotCalm();

    /// @notice The adapter has not been wired yet (address is zero).
    error AdapterNotSet();

    /// @notice An attempt was made to set the adapter after it was already configured.
    error AdapterAlreadySet();

    /// @notice Caller is not the deployer that is authorized to perform one-time adapter wiring.
    /// @dev    `setAdapter` is deployer-gated (captured in the constructor as an immutable)
    ///         so the factory — which deploys the wrapper and then calls `setAdapter` in the
    ///         same transaction — can perform atomic wiring without holding a governance role.
    error NotDeployer(address caller);

    /// @notice The two deposit tokens supplied to the constructor are identical.
    error TokensIdentical();

    // ─── Events ──────────────────────────────────────────────────────────

    /// @notice Emitted when a new dual-asset position is opened or topped up.
    /// @param positionId    Resolved position identifier (new or existing open position).
    /// @param user          Position owner.
    /// @param licenseId     Off-chain license reference from the signed action.
    /// @param amount0       token0 supplied by the caller before dust return.
    /// @param amount1       token1 supplied by the caller before dust return.
    /// @param principalUsdc USDC-equivalent cost basis recorded for this deposit.
    /// @param shares        Provider (VaultConcLiq) shares minted and held by the wrapper.
    /// @param referrer      L1 referrer from the signed action, or address(0).
    event Deposited(
        uint256 indexed positionId,
        address indexed user,
        uint256 indexed licenseId,
        uint256 amount0,
        uint256 amount1,
        uint256 principalUsdc,
        uint256 shares,
        address referrer
    );

    /// @notice Emitted on a signed withdrawal (partial or full).
    /// @param positionId    The position affected.
    /// @param user          Position owner (msg.sender).
    /// @param userAmountUsdc   Signed USDC-equivalent amount routed to the user.
    /// @param protocolAmountUsdc Signed USDC-equivalent amount routed to treasury.
    /// @param amount0ToUser token0 transferred to the user.
    /// @param amount1ToUser token1 transferred to the user.
    /// @param amount0ToTreasury token0 transferred to treasury.
    /// @param amount1ToTreasury token1 transferred to treasury.
    /// @param closed        True if the position was fully closed.
    event Withdrawn(
        uint256 indexed positionId,
        address indexed user,
        uint256 userAmountUsdc,
        uint256 protocolAmountUsdc,
        uint256 amount0ToUser,
        uint256 amount1ToUser,
        uint256 amount0ToTreasury,
        uint256 amount1ToTreasury,
        bool closed
    );

    /// @notice Emitted on a signature-free, principal-only emergency exit.
    /// @param positionId         The position affected.
    /// @param user               Position owner (msg.sender).
    /// @param amount0ToUser      token0 returned to the user (principal-equivalent).
    /// @param amount1ToUser      token1 returned to the user (principal-equivalent).
    /// @param amount0ToTreasury  token0 surplus above principal forwarded to treasury.
    /// @param amount1ToTreasury  token1 surplus above principal forwarded to treasury.
    event EmergencyRedeemed(
        uint256 indexed positionId,
        address indexed user,
        uint256 amount0ToUser,
        uint256 amount1ToUser,
        uint256 amount0ToTreasury,
        uint256 amount1ToTreasury
    );

    /// @notice Emitted when the adapter is wired to the wrapper (one-time operation).
    event AdapterSet(address indexed adapter);

    // ─── Views ───────────────────────────────────────────────────────────

    /// @notice First deposit token of the pair. Immutable after deployment.
    function depositToken0() external view returns (address);

    /// @notice Second deposit token of the pair. Immutable after deployment.
    function depositToken1() external view returns (address);

    /// @notice The `IDualAssetLpVaultAdapter` instance wired to this wrapper.
    ///         Set via `setAdapter` after deployment (one-time, deployer-gated).
    function adapter() external view returns (address);

    /// @notice The dual-asset valuation oracle. Immutable after deployment.
    function oracle() external view returns (address);

    /// @notice Preview token amounts returned for a given share count.
    /// @dev    Forwards to `adapter.previewWithdraw`. Accurate only during calm.
    /// @param _shares  Provider (VaultConcLiq) share count.
    /// @return amount0 Expected token0 returned.
    /// @return amount1 Expected token1 returned.
    function previewWithdraw(uint256 _shares) external view returns (uint256 amount0, uint256 amount1);

    /// @notice Max USDC protocol fee chargeable on a withdraw of this position (fee-only cap).
    /// @dev    Clearer alias of `availableProfitUsdc` for dual-asset: it is the CEILING on
    ///         the signed `protocolAmount`, NOT the user's profit. Equals
    ///         `min(pending fee-only USDC, net gain USDC)`. The user's take is the value
    ///         of their shares (`previewWithdraw`), separate from this cap.
    /// @param _positionId Position to query.
    /// @return maxFeeUsdc Maximum `protocolAmount` (USDC) a withdraw may charge.
    function maxProtocolFeeUsdc(uint256 _positionId) external view returns (uint256 maxFeeUsdc);

    /// @notice Whether the underlying VaultConcLiq pool is currently calm.
    function isCalm() external view returns (bool);

    // ─── Functions ─────────────────────────────────────────────────────────

    /// @notice Wire the adapter to this wrapper. One-time; deployer-gated.
    /// @dev    Separate from the constructor to break the circular deploy dependency:
    ///         the adapter's constructor requires the wrapper address, so the wrapper
    ///         must be deployed first without knowing the adapter address.
    ///         Callable only by the address that deployed the wrapper (captured as an
    ///         immutable `_deployer` in the constructor) — typically the factory, which
    ///         calls this atomically in the same deploy transaction (no front-run window).
    ///         Manual (non-factory) deployments must call `setAdapter` in the same tx
    ///         or script as deployment.
    ///         Reverts `NotDeployer` if `msg.sender != _deployer`.
    ///         Reverts `AdapterAlreadySet` if called again.
    ///         Reverts `ZeroAddress` if `_adapter` is the zero address.
    /// @param _adapterAddress The `IDualAssetLpVaultAdapter` instance wired to this wrapper.
    function setAdapter(address _adapterAddress) external;

    /// @notice Create or top up the caller's open position for a backend-authorized
    ///         dual-asset deposit.
    /// @dev    Requires a valid `SignedAction` of type `Deposit` with
    ///         `positionId == 0`, `userAmount == 0`, `protocolAmount == 0`, and
    ///         `amount == uint256(keccak256(abi.encode(_amount0, _amount1, _minShares)))`.
    ///         The amount field is a commitment, not a token or USDC value; the
    ///         backend signer must compute it from the exact authorized deposit pair
    ///         AND share floor.
    ///         The signed `licenseId` and `referrer` are extracted from the payload.
    ///         Pulls `_amount0` token0 and `_amount1` token1 from `msg.sender`,
    ///         forwards them to the adapter (which deposits into VaultConcLiq and
    ///         returns provider shares + any unspent dust). Dust is forwarded back
    ///         to `msg.sender`. `principalUsdc` is fixed as the USDC value of
    ///         consumed tokens via the dual oracle. If an open position already
    ///         exists for `(msg.sender, licenseId)`, the deposit tops it up
    ///         (additive shares + principalUsdc; `openedAt` unchanged). Otherwise
    ///         a fresh position is created.
    ///         Reverts `NotCalm` if the pool is not in a calm state.
    ///         Reverts `ZeroShares` if the provider mints zero shares.
    ///         Reverts `InvalidDepositAction` if routing fields are non-zero where
    ///         they must be zero for a deposit. Reverts `DepositAmountsMismatch` if
    ///         either calldata token amount or `_minShares` differs from the signed
    ///         commitment. Reverts `ZeroMinShares` if the committed floor is zero.
    /// @param _action    Signed deposit authorization (type `Deposit`).
    /// @param _sig       Backend signature over `_action`.
    /// @param _amount0   token0 to deposit.
    /// @param _amount1   token1 to deposit.
    /// @param _minShares Minimum provider shares to receive. Part of the signed
    ///                   commitment and must be non-zero — it is the only defence
    ///                   against permissionless share-price dilution.
    /// @return positionId Resolved position identifier (new or existing open position).
    function deposit(
        SignedAction calldata _action,
        bytes calldata _sig,
        uint256 _amount0,
        uint256 _amount1,
        uint256 _minShares
    ) external returns (uint256 positionId);

    /// @notice Partial or full withdrawal of a dual-asset position.
    /// @dev    Requires a valid `SignedAction` of type `Withdraw`. `_action.amount`
    ///         is the number of provider (VaultConcLiq) shares to redeem, or
    ///         `type(uint256).max` as a sentinel for a full close of all position
    ///         shares.
    ///         `_action.userAmount` and `_action.protocolAmount` are USDC-denominated
    ///         and represent the signed routing split. The wrapper settles in-kind
    ///         (token0 + token1) proportional to the split; it never swaps.
    ///         Guards for fee-only accounting:
    ///           - net-negative guard: reverts `FeeOnLoss` if the withdrawn portion
    ///             is not in net profit and `protocolAmount > 0`.
    ///           - fee-only cap: reverts `FeeExceedsFeeOnlyProfit` if `protocolAmount`
    ///             exceeds min(pendingFeeUsdc, netGainUsdc) for the withdrawn portion.
    ///             Unharvested fees are not yet attributable; harvest lag is acceptable.
    ///           - slippage floor: reverts `InsufficientRedeemed` if the total
    ///             redeemed USDC value < `userAmount + protocolAmount`.
    ///         Reverts `NotCalm` if the pool is not calm.
    ///         `withdrawMany` is NOT present on this interface because dual-asset
    ///         multi-position aggregation would need proportional two-token routing.
    /// @param _action     Signed withdraw authorization.
    /// @param _sig        Backend signature over `_action`.
    /// @param _breakdown  Per-recipient, per-token bps split of the protocol fee,
    ///                    committed by `_action.protocolSplitHash`. Must contain entries
    ///                    for both pool tokens (each summing to 10_000 bps) when a fee is
    ///                    charged; empty when `protocolSplitHash == 0` (no fee split).
    /// @param _minAmount0 Minimum token0 to receive from the provider (slippage guard).
    /// @param _minAmount1 Minimum token1 to receive from the provider (slippage guard).
    function withdraw(
        SignedAction calldata _action,
        bytes calldata _sig,
        ProtocolSplitShare[] calldata _breakdown,
        uint256 _minAmount0,
        uint256 _minAmount1
    ) external;

    /// @notice Emergency exit. No backend signature; returns principal only.
    /// @dev    Bypasses all off-chain policy and does NOT check `isCalm()`. The
    ///         provider permits exit while the pool remains non-calm after the
    ///         same-block deposit guard has elapsed; a deposit followed by emergency
    ///         redeem at the same timestamp can still require waiting for a later block.
    ///         Remaining provider capital may stay idle until a later deposit,
    ///         harvest, or tick-management action re-deploys it.
    ///         Redeems ALL position shares via the adapter, returns the
    ///         principal-equivalent token amounts to the caller in-kind, and routes any
    ///         surplus above recorded principal to treasury. If value <= principal, the
    ///         user receives ALL tokens and treasury receives nothing.
    ///         Reverts `ZeroMinOut` if BOTH `_minOut0 == 0 AND _minOut1 == 0`
    ///         (anti-sandwich; both-zero is rejected because the caller must supply
    ///         at least one explicit token floor).
    ///         Reverts `NotPositionOwner` if caller is not the position owner.
    ///         Reverts `PositionNotActive` if position is not active.
    /// @param _positionId Target position to emergency-exit.
    /// @param _minOut0    Minimum token0 out from the provider (slippage guard).
    /// @param _minOut1    Minimum token1 out from the provider (slippage guard).
    function emergencyRedeem(uint256 _positionId, uint256 _minOut0, uint256 _minOut1) external;
}

contracts/vaults/dual-asset-conc-liq/adapters/lp-vault/IDualAssetLpVaultAdapter.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

/// @title IDualAssetLpVaultAdapter
/// @notice Adapter boundary between a WADZ dual-asset wrapper and the vendored
///         `VaultConcLiq` concentrated-liquidity provider. One stateless instance
///         is deployed per WADZ LP vault and wired 1:1 to its wrapper.
/// @dev    Custody model: the adapter is stateless and holds ZERO token0/token1/shares
///         between calls. The wrapper is the ONLY authorized caller and the custodian
///         of all provider (VaultConcLiq) shares between calls.
///
///         Because `VaultConcLiq.deposit` mints shares to `msg.sender` (no receiver
///         param), shares are minted to the ADAPTER during the deposit call. The
///         adapter immediately transfers them to the wrapper before returning. Any
///         unspent deposit dust (token0/token1 not consumed by the pool ratio) is
///         also swept back to the wrapper so the adapter leaves zero balance.
///
///         On withdraw, the wrapper first transfers the shares to the adapter. The
///         adapter calls `VaultConcLiq.withdraw` (burns the adapter's shares, sends
///         token0/token1 to the adapter), then forwards all received amounts to the
///         wrapper. The adapter again leaves zero balance.
///
///         The interface omits a `receiver` parameter on every mutating function —
///         all assets, shares, and dust flow exactly to or from the wrapper and never
///         to an arbitrary address.
interface IDualAssetLpVaultAdapter {
    // ─── Errors ──────────────────────────────────────────────────────────

    /// @notice Caller is not the wired wrapper.
    error OnlyWrapper(address caller);

    /// @notice A zero address was supplied where a real address is required.
    error ZeroAddress();

    // ─── Events ──────────────────────────────────────────────────────────

    /// @notice Emitted when the adapter deposits into the provider vault.
    /// @param amount0  token0 actually consumed by the provider.
    /// @param amount1  token1 actually consumed by the provider.
    /// @param shares   VaultConcLiq shares minted and forwarded to the wrapper.
    event AdapterDeposited(uint256 amount0, uint256 amount1, uint256 shares);

    /// @notice Emitted when the adapter withdraws from the provider vault.
    /// @param shares   VaultConcLiq shares burned.
    /// @param amount0  token0 forwarded to the wrapper.
    /// @param amount1  token1 forwarded to the wrapper.
    event AdapterWithdrawn(uint256 shares, uint256 amount0, uint256 amount1);

    // ─── Views ───────────────────────────────────────────────────────────

    /// @notice The wrapper this adapter instance serves; the only authorized
    ///         caller and the custodian of all provider shares. Immutable.
    function wrapper() external view returns (address);

    /// @notice The `VaultConcLiq` provider vault; also the ERC-20 share token.
    ///         Immutable.
    function vault() external view returns (address);

    /// @notice First token of the pair (cached from `VaultConcLiq.wants()`).
    ///         Immutable.
    function token0() external view returns (address);

    /// @notice Second token of the pair (cached from `VaultConcLiq.wants()`).
    ///         Immutable.
    function token1() external view returns (address);

    /// @notice Preview token amounts returned for a given share amount.
    /// @dev    Forwards directly to `VaultConcLiq.previewWithdraw`. Values are only
    ///         reliable while the underlying pool is calm.
    /// @param _shares  Number of provider shares.
    /// @return amount0 Expected token0 returned.
    /// @return amount1 Expected token1 returned.
    function previewWithdraw(uint256 _shares) external view returns (uint256 amount0, uint256 amount1);

    /// @notice Preview shares minted for given token amounts.
    /// @dev    Forwards directly to `VaultConcLiq.previewDeposit`. Values are only
    ///         reliable while the underlying pool is calm.
    /// @param _amount0     token0 to deposit.
    /// @param _amount1     token1 to deposit.
    /// @return shares      Expected shares minted.
    /// @return amount0Used token0 the provider will actually consume.
    /// @return amount1Used token1 the provider will actually consume.
    /// @return fee0        Swap fee charged in token0.
    /// @return fee1        Swap fee charged in token1.
    function previewDeposit(
        uint256 _amount0,
        uint256 _amount1
    ) external view returns (uint256 shares, uint256 amount0Used, uint256 amount1Used, uint256 fee0, uint256 fee1);

    /// @notice Current total token balances held by the provider strategy (across
    ///         vault + strategy contracts). Off-chain/operator view; the wrapper
    ///         values positions via `previewWithdraw`, not via this function.
    /// @return amount0 Total token0 under management.
    /// @return amount1 Total token1 under management.
    function balances() external view returns (uint256 amount0, uint256 amount1);

    /// @notice Total VaultConcLiq shares outstanding. Off-chain/operator view;
    ///         the wrapper does not use this to compute proportional position value
    ///         (it uses `previewWithdraw` directly on the position's share count).
    function totalSupply() external view returns (uint256);

    /// @notice Whether the pool is currently calm (safe for deposits). Forwards
    ///         to `VaultConcLiq.isCalm()`. The wrapper SHOULD check this before
    ///         routing a deposit; the provider enforces it internally as well.
    function isCalm() external view returns (bool);

    /// @notice Current cumulative per-share fee indexes from the provider strategy.
    /// @dev    Reads `cumulativeFee0PerShare` and `cumulativeFee1PerShare` from
    ///         the provider strategy through the vault's `strategy()` reference.
    ///         The indexes are 1e36-scaled monotonically increasing sums of
    ///         net-to-LP fees per share at each harvest.
    ///         The wrapper uses the delta from a position's snapshot index to
    ///         compute fee-only attributable profit without importing provider
    ///         contracts directly.
    /// @return cumulativeFee0PerShare  Cumulative token0 fees per share (1e36 precision).
    /// @return cumulativeFee1PerShare  Cumulative token1 fees per share (1e36 precision).
    function feeIndexes() external view returns (uint256 cumulativeFee0PerShare, uint256 cumulativeFee1PerShare);

    // ─── Functions ───────────────────────────────────────────────────────

    /// @notice Deposit token0/token1 into the provider vault.
    /// @dev    Pre-condition: the wrapper has already transferred `_amount0` of
    ///         token0 AND `_amount1` of token1 to this adapter before calling.
    ///         The adapter `forceApprove`s the provider and calls
    ///         `VaultConcLiq.deposit(_amount0, _amount1, _minShares)`.
    ///         Because `VaultConcLiq` mints shares to `msg.sender`, shares land
    ///         on the adapter; the adapter immediately transfers them to the wrapper.
    ///         Any unspent token0/token1 dust is swept back to the wrapper.
    ///         Approvals are reset to zero after the call. The adapter holds zero
    ///         balance on return.
    ///
    ///         NOTE: the provider may consume less than `_amount0`/`_amount1`
    ///         depending on the current pool ratio; dust is always returned to
    ///         the wrapper. This diverges from the ERC4626 adapter, where the
    ///         provider always consumes the full asset amount.
    /// @param _amount0   token0 transferred to the adapter by the wrapper.
    /// @param _amount1   token1 transferred to the adapter by the wrapper.
    /// @param _minShares Slippage guard; `VaultConcLiq` reverts if shares < `_minShares`.
    /// @return shares    VaultConcLiq shares minted and forwarded to the wrapper.
    /// @return consumed0 token0 actually consumed by the provider.
    /// @return consumed1 token1 actually consumed by the provider.
    function deposit(
        uint256 _amount0,
        uint256 _amount1,
        uint256 _minShares
    ) external returns (uint256 shares, uint256 consumed0, uint256 consumed1);

    /// @notice Withdraw token0/token1 from the provider vault by burning shares.
    /// @dev    Pre-condition: the wrapper has already transferred `_shares` of the
    ///         VaultConcLiq share token to this adapter before calling.
    ///         The adapter calls `VaultConcLiq.withdraw(_shares, _minAmount0,
    ///         _minAmount1)`, which burns the adapter's shares and sends token0/token1
    ///         back to the adapter. The adapter then forwards ALL received amounts to
    ///         the wrapper. The adapter holds zero balance on return.
    ///
    ///         NOTE: per-token min-out slippage is enforced by the provider itself via
    ///         the explicit `_minAmount0`/`_minAmount1` parameters. WADZ single-asset
    ///         ERC4626 redeems use the same explicit min-out pattern at the adapter
    ///         boundary, so no separate bps-based max-loss config is needed.
    /// @param _shares      VaultConcLiq shares transferred to the adapter by the wrapper.
    /// @param _minAmount0  Minimum token0 to receive; passed through to the provider.
    /// @param _minAmount1  Minimum token1 to receive; passed through to the provider.
    /// @return amount0     token0 forwarded to the wrapper.
    /// @return amount1     token1 forwarded to the wrapper.
    function withdraw(
        uint256 _shares,
        uint256 _minAmount0,
        uint256 _minAmount1
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Emergency variant of `withdraw` used only by the wrapper's
    ///         principal-only `emergencyRedeem`.
    /// @dev    Identical custody flow to `withdraw` (burns the adapter's shares,
    ///         forwards token0/token1 to the wrapper) but routes through
    ///         `VaultConcLiq.emergencyWithdraw`, which skips the provider's same-block
    ///         `lastDeposit` calm gate. The vault must have the adapter registered as
    ///         its `emergencyCaller`. The wrapper enforces the per-position same-block
    ///         anti-sandwich guard before calling this.
    /// @param _shares      VaultConcLiq shares transferred to the adapter by the wrapper.
    /// @param _minAmount0  Minimum token0 to receive; passed through to the provider.
    /// @param _minAmount1  Minimum token1 to receive; passed through to the provider.
    /// @return amount0     token0 forwarded to the wrapper.
    /// @return amount1     token1 forwarded to the wrapper.
    function emergencyWithdraw(
        uint256 _shares,
        uint256 _minAmount0,
        uint256 _minAmount1
    ) external returns (uint256 amount0, uint256 amount1);
}

contracts/vaults/shared/IWadzVaultCore.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

import { VaultKind, VaultState, Position } from "../../platform/types/WadzTypes.sol";

/// @title IWadzVaultCore
/// @notice Kind-agnostic interface every WADZ wrapper implements. Carries only
///         metadata, USDC-denominated valuation, and position queries — the
///         surface that is common regardless of vault kind.
/// @dev    User action methods (deposit/claim/withdraw/emergencyRedeem) are NOT
///         here; they live on the kind-specific interfaces because their
///         signatures and life cycles differ.
interface IWadzVaultCore {
    // ─── Errors ──────────────────────────────────────────────────────────

    /// @notice The prospective rewards treasury does not recognize this wrapper.
    error WrapperNotRegistered(address wrapper, address treasury);

    // ─── Events ──────────────────────────────────────────────────────────

    /// @notice Emitted when governance changes the vault lifecycle state.
    event VaultStateChanged(VaultState previousState, VaultState newState);

    /// @notice Emitted when governance changes the protocol treasury destination.
    /// @param previousTreasury Previous protocol treasury destination.
    /// @param newTreasury New protocol treasury destination.
    event TreasurySet(address indexed previousTreasury, address indexed newTreasury);

    // ─── Governance ──────────────────────────────────────────────────────

    /// @notice Change the protocol treasury destination for future routing.
    /// @dev    Callable only by the wrapper governance address. The wrapper must
    ///         already be registered on the prospective `WadzRewardsVault`.
    ///         An EOA or contract without the rewards-vault interface may revert
    ///         directly during interface decoding rather than with
    ///         `WrapperNotRegistered`.
    /// @param _treasury New protocol treasury destination.
    function setTreasury(address _treasury) external;

    // ─── Views: metadata ───────────────────────────────────────────────────

    /// @notice Returns the vault kind. Immutable after deployment.
    function vaultKind() external view returns (VaultKind);

    /// @notice The asset used for all WADZ accounting (always USDC in the MVP).
    function accountingAsset() external view returns (address);

    /// @notice Destination for protocol routing and emergency surplus.
    function treasury() external view returns (address);

    /// @notice Returns the current vault lifecycle state.
    function vaultState() external view returns (VaultState);

    // ─── Views: valuation (USDC-denominated) ─────────────────────────────────

    /// @notice Current total value of a position in USDC. Reverts on stale oracle.
    function positionValueUsdc(uint256 _positionId) external view returns (uint256);

    /// @notice Recognizable profit in USDC for a position, net of claimed profit.
    /// @dev    For single-asset vaults this is share-price appreciation in USDC.
    ///         For dual-asset vaults it MUST be fee-only, not NAV change.
    function availableProfitUsdc(uint256 _positionId) external view returns (uint256);

    // ─── Views: position queries ─────────────────────────────────────────────

    /// @notice Returns the full position record.
    function getPosition(uint256 _positionId) external view returns (Position memory);

    /// @notice Returns all position ids owned by `_wallet`.
    function walletPositions(address _wallet) external view returns (uint256[] memory);

    /// @notice Returns all position ids associated with `_licenseId`.
    function licensePositions(uint256 _licenseId) external view returns (uint256[] memory);

    /// @notice Returns the currently open position for `_wallet` and `_licenseId`.
    /// @dev Returns 0 when the pair has no open position in this vault.
    function openPositionOf(address _wallet, uint256 _licenseId) external view returns (uint256 positionId);
}

contracts/vaults/single-asset-sync/ISASWVault.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

import { IWadzVaultCore } from "../shared/IWadzVaultCore.sol";
import { SignedAction } from "../../platform/authorizer/IWadzActionAuthorizer.sol";
import { ProtocolSplitShare } from "../../platform/rewards/IWadzRewardsVault.sol";

/// @title ISASWVault
/// @notice Vault-kind interface for SINGLE_ASSET_SYNC. Adds the single-asset
///         action surface to `IWadzVaultCore`. Backed by a generic ERC4626
///         adapter; protocol-agnostic.
/// @dev    Adapted to the MVP off-chain model: `deposit`/`claim`/`withdraw` are
///         authorized by a backend EIP-712 `SignedAction` instead of the
///         policy-hook arguments in the original interface sketch. The wrapper
///         executes the signed `userAmount`/`protocolAmount` routing exactly and
///         never recomputes the split. `emergencyRedeem` is signature-free and
///         principal-only. Withdrawal is synchronous at the wrapper level but may
///         be liquidity-limited at the provider boundary (redeem can revert).
interface ISASWVault is IWadzVaultCore {
    // ─── Errors ──────────────────────────────────────────────────────────

    /// @notice Signed routing is inconsistent (userAmount + protocolAmount != amount).
    error InvalidRouting(uint256 amount, uint256 userAmount, uint256 protocolAmount);

    /// @notice A deposit action carried a non-zero positionId or a non-zero split.
    error InvalidDepositAction();

    /// @notice Caller is not the owner of the target position.
    error NotPositionOwner(uint256 positionId, address caller);

    /// @notice Target position is not in the required status for the operation.
    error PositionNotActive(uint256 positionId);

    /// @notice Provided amount is zero where a positive amount is required.
    error ZeroAmount();

    /// @notice Requested claim amount exceeds the position's available profit.
    error InsufficientProfit(uint256 requested, uint256 available);

    /// @notice Assets redeemed from the provider are below the signed routing total
    ///         (userAmount + protocolAmount) that must be paid out.
    error InsufficientRedeemed(uint256 redeemed, uint256 owed);

    /// @notice A partial withdrawal requested more than the position's current value.
    ///         A full close must use the `type(uint256).max` sentinel for `amount`.
    error WithdrawExceedsPositionValue(uint256 requested, uint256 available);

    /// @notice depositAsset/oracle configuration is inconsistent: USDC must have no
    ///         oracle, and a non-USDC asset must have one.
    error OracleConfigMismatch();

    /// @notice A deposit minted zero provider shares (e.g. dust amount rounded down).
    error ZeroShares();

    /// @notice A deposit minted fewer provider shares than the caller's slippage floor.
    error InsufficientShares(uint256 minted, uint256 minShares);

    /// @notice The signed `licenseId` does not match the position's stored license.
    ///         Licenses are fixed at deposit and cannot change for a position.
    error LicenseMismatch(uint256 provided, uint256 expected);

    /// @notice `actions` and `sigs` arrays passed to `withdrawMany` have different lengths.
    error LengthMismatch(uint256 actionsLength, uint256 sigsLength);

    /// @notice `withdrawMany` was called with an empty batch.
    error EmptyBatch();

    // ─── Events ──────────────────────────────────────────────────────────

    /// @notice Emitted when a new position is opened by a signed deposit.
    event Deposited(
        uint256 indexed positionId,
        address indexed user,
        uint256 indexed licenseId,
        uint256 assets,
        uint256 principalUsdc,
        uint256 receiptAmount,
        address referrer
    );

    /// @notice Emitted when profit is claimed without closing the position.
    event ProfitClaimed(
        uint256 indexed positionId,
        address indexed user,
        uint256 userAmount,
        uint256 protocolAmount,
        uint256 recognizedProfitUsdc
    );

    /// @notice Emitted on a signed withdrawal (partial or full).
    event Withdrawn(
        uint256 indexed positionId,
        address indexed user,
        uint256 userAmount,
        uint256 protocolAmount,
        bool closed
    );

    /// @notice Emitted on a signature-free, principal-only emergency exit.
    event EmergencyRedeemed(
        uint256 indexed positionId,
        address indexed user,
        uint256 principalToUser,
        uint256 surplusToTreasury
    );

    // ─── Views ───────────────────────────────────────────────────────────

    /// @notice The single asset accepted at deposit (e.g. USDC, USDT, USDe).
    function depositAsset() external view returns (address);

    /// @notice The ERC4626 adapter instance wired to this wrapper. Immutable.
    function adapter() external view returns (address);

    /// @notice Preview the depositAsset value of a provider-share amount.
    function previewRedeem(uint256 _receiptAmount) external view returns (uint256 assetsOut);

    /// @notice Claimable profit expressed in depositAsset units (not USDC).
    /// @dev    Lets the backend sign a `claim` `amount` directly without an off-chain
    ///         USDC->asset conversion. Equals `availableProfitUsdc` for a USDC vault;
    ///         for a volatile asset it is the asset amount whose USDC value equals the
    ///         NAV profit. Returns 0 if the position is not in profit.
    function availableProfitAssets(uint256 _positionId) external view returns (uint256 profitAssets);

    // ─── Functions ─────────────────────────────────────────────────────────

    /// @notice Create or top up the caller's open position for a backend-authorized deposit.
    /// @dev    Requires a valid `SignedAction` of type `Deposit` with
    ///         `positionId == 0` and zero routing amounts. Pulls `amount` of
    ///         depositAsset from `msg.sender`, deposits via the adapter (shares
    ///         held by the wrapper), and fixes `principalUsdc` via the oracle. If an
    ///         open position already exists for `(msg.sender, licenseId)`, the
    ///         deposit tops it up by adding receipt shares, USDC principal, and
    ///         principal in depositAsset units. Otherwise a fresh position is created.
    ///
    ///         `_minShares` is the caller's slippage floor on the provider shares minted
    ///         for this deposit. A bare `shares != 0` check is not protection: in an
    ///         ERC4626 susceptible to donation/inflation, a third party can front-run the
    ///         deposit to inflate the price per share so that a large deposit mints a
    ///         single share — non-zero, therefore accepted. The floor is plain calldata
    ///         rather than a signed field because binding it would require a new
    ///         `SignedAction` member and a new `SIGNED_ACTION_TYPEHASH`, i.e. redeploying
    ///         the authorizer and re-versioning every backend signature; the deposit
    ///         `amount` itself is signed, which bounds the exposure.
    /// @param _action    Signed deposit authorization.
    /// @param _signature Backend signature over `_action`.
    /// @param _minShares Minimum provider shares that must be minted for this deposit.
    /// @return positionId Resolved position identifier (new or existing open position).
    function deposit(
        SignedAction calldata _action,
        bytes calldata _signature,
        uint256 _minShares
    ) external returns (uint256 positionId);

    /// @notice Claim accrued profit without closing the position.
    /// @dev    Requires a valid `SignedAction` of type `Claim`. `amount` is the
    ///         profit realized in depositAsset units and must equal
    ///         `userAmount + protocolAmount`. The wrapper pays exactly `userAmount`
    ///         to the user and exactly `protocolAmount` to treasury; any redeem
    ///         surplus above the signed split is returned to the position owner,
    ///         never to treasury.
    function claim(
        SignedAction calldata _action,
        bytes calldata _signature,
        ProtocolSplitShare[] calldata _breakdown
    ) external;

    /// @notice Partial or full withdrawal of a position.
    /// @dev    Requires a valid `SignedAction` of type `Withdraw`. For a partial
    ///         withdrawal, `amount` is the gross depositAsset to redeem and must
    ///         equal `userAmount + protocolAmount` and be at most the position's
    ///         current value. For a full close, the backend signs
    ///         `amount == type(uint256).max`; the position is then fully redeemed and
    ///         closed. In both cases the wrapper pays exactly `userAmount` to the user
    ///         and exactly `protocolAmount` to treasury, and returns any redeem
    ///         surplus above the signed split to the position owner — protocol never
    ///         captures position growth beyond the signed split.
    function withdraw(
        SignedAction calldata _action,
        bytes calldata _signature,
        ProtocolSplitShare[] calldata _breakdown
    ) external;

    /// @notice Emergency exit. No backend signature; returns principal only.
    /// @dev    Bypasses all off-chain policy. Redeems the position's shares,
    ///         returns up to the recorded principal to the owner, and routes any
    ///         surplus to treasury.
    /// @param _positionId Target position.
    /// @param _minOut     Minimum depositAsset out from the provider (slippage guard).
    function emergencyRedeem(uint256 _positionId, uint256 _minOut) external;

    /// @notice Aggregate multiple withdrawal intents for this vault in one
    ///         transaction, with a single provider redeem and a single routing call.
    /// @dev    All `_actions` must be signed `Withdraw` actions for positions owned by
    ///         `msg.sender` in this vault. Each action is authorized independently
    ///         (nonce consumed per action); all position effects are applied before the
    ///         single external redeem (CEI). A single `_redeemShares` call covers
    ///         `Σ sharesToRedeem_i` and a single `_routeSplit` routes the aggregate:
    ///         treasury receives `Σ protocolAmount_i`; the owner receives
    ///         `assetsOut − Σ protocolAmount_i` (includes any aggregate surplus).
    ///         Per-position `Withdrawn` events are emitted inside the loop, after each
    ///         position's effects and before the external redeem.
    ///
    ///         Reverts `LengthMismatch` if array lengths differ; `EmptyBatch` if empty.
    ///         The whole batch is atomic: if any individual action reverts (wrong owner,
    ///         expired signature, already-closed position, etc.) the entire tx reverts.
    ///         Multiple partial entries may reference the same active position; they are
    ///         processed sequentially against that position's progressively reduced
    ///         receipt/principal state. If an earlier entry closes a position, any later
    ///         entry for that same position reverts `PositionNotActive`, reverting the
    ///         whole batch.
    ///
    ///         Slippage floor: aggregate `totalUser + totalProtocol`; if the single
    ///         provider redeem returns less, the whole batch reverts `InsufficientRedeemed`.
    /// @param _actions Signed `Withdraw` actions, one per withdrawal intent.
    /// @param _sigs    Backend signatures over each corresponding action.
    function withdrawMany(
        SignedAction[] calldata _actions,
        bytes[] calldata _sigs,
        ProtocolSplitShare[][] calldata _breakdowns
    ) external;
}

contracts/vaults/single-asset-sync/adapters/erc4626/IGenericERC4626Adapter.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

/// @title IGenericERC4626Adapter
/// @notice Adapter boundary for any standard ERC4626 provider vault (MetaMorpho,
///         Yearn v3, etc.). Protocol-agnostic: no provider is special-cased.
/// @dev    Custody model: the adapter is a stateless instance wired 1:1 to a
///         wrapper. The wrapper is the only authorized caller. On deposit, the
///         wrapper sends `assets` to the adapter and the adapter deposits into the
///         underlying ERC4626 with `receiver = wrapper`, so provider shares are
///         minted to and held by the WRAPPER — never the adapter, never the user.
///         The adapter holds zero balance between calls. The interface omits a
///         `receiver` parameter on purpose, so shares cannot leak outside WADZ
///         custody.
interface IGenericERC4626Adapter {
    // ─── Views ───────────────────────────────────────────────────────────

    /// @notice The wrapper this adapter instance serves; the only authorized
    ///         caller and the receiver/owner of all provider shares. Immutable.
    function wrapper() external view returns (address);

    /// @notice The underlying asset of the ERC4626 vault.
    function asset() external view returns (address);

    /// @notice The ERC4626 vault (and provider share token) this adapter wraps.
    function vault4626() external view returns (address);

    /// @notice Preview assets returned for a given provider-share amount.
    function previewRedeem(uint256 _shares) external view returns (uint256 assetsOut);

    /// @notice Current provider share price in asset units, scaled to 1e18.
    function sharePriceE18() external view returns (uint256);

    // ─── Functions ─────────────────────────────────────────────────────────

    /// @notice Deposit `_assets` (already transferred to the adapter) into the
    ///         underlying ERC4626 vault. Returns provider shares minted to the wrapper.
    function deposit(uint256 _assets) external returns (uint256 shares);

    /// @notice Redeem `_shares` (already transferred to the adapter) from the
    ///         underlying ERC4626 vault, sending assets to the wrapper.
    /// @param _shares       Provider shares to redeem.
    /// @param _minAssetsOut Slippage guard; reverts if assetsOut < `_minAssetsOut`.
    /// @return assetsOut    Assets returned to the wrapper.
    function redeem(uint256 _shares, uint256 _minAssetsOut) external returns (uint256 assetsOut);
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.