Skip to content
Verified contractExactBUSL-1.1

AaveAdapterConfig

Address0x01d0e278be41a3b4ce5e747358f1cdf0dbb28ff8
Balance

0 ETH

 

Transactions

0

 

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
Via IR
yes
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,400,235
Creation transaction
0x71fa13f683…e8f7314e17

33 files

src/applications/aave/AaveAdapterConfig.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

import {AaveAdapterTemplateUpg} from "./abstract/AaveAdapterTemplateUpg.sol";
import {Errors as AdapterErrors} from "./lib/types/Errors.sol";
import {Events as AdapterEvents} from "./lib/types/Events.sol";
import {IAaveAdapterConfig} from "./interfaces/IAaveAdapterConfig.sol";
import {IERC165} from "../../../lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol";
import {ILiquidationLiquidityProvider} from "./interfaces/ILiquidationLiquidityProvider.sol";
import {IAaveAdapterPositionResolver} from "./interfaces/IAaveAdapterPositionResolver.sol";

/// @title AaveAdapterConfig
/// @notice Unified config for managing LLPs, Resolvers, and position size parameters for the Aave integration adapter
contract AaveAdapterConfig is IAaveAdapterConfig, AaveAdapterTemplateUpg {
    // ═══════════════════════════════════════════════════════════════════════════
    //                              IMMUTABLES
    // ═══════════════════════════════════════════════════════════════════════════

    /// @notice The adapter address that resolvers must be configured for
    address public immutable ADAPTER;

    // ═══════════════════════════════════════════════════════════════════════════
    //                                  STORAGE
    // ═══════════════════════════════════════════════════════════════════════════

    /// @notice Tracks registered LLPs
    mapping(address => bool) public isRegisteredLLP;

    /// @notice Tracks enabled/disabled status of LLPs
    mapping(address => bool) public llpEnabled;

    /// @notice Tracks registered resolvers
    mapping(address => bool) public isRegisteredResolver;

    /// @notice Position size boundary parameters
    PositionSizeParams internal positionSizeParams;

    /// @dev Storage gap for future upgrades
    uint256[50] private __gap;

    /// @param adapter_ The adapter address that resolvers must reference
    constructor(address adapter_) {
        if (adapter_ == address(0)) revert AdapterErrors.ZeroAddress();
        ADAPTER = adapter_;
        _disableInitializers();
    }

    // ═══════════════════════════════════════════════════════════════════════════
    //                                INITIALIZER
    // ═══════════════════════════════════════════════════════════════════════════

    /// @notice Initialize the AaveAdapterConfig
    /// @param admin_ Address with admin role
    function initialize(address admin_) external initializer {
        if (admin_ == address(0)) revert AdapterErrors.ZeroAddress();
        __TBVTemplateUpg_init(admin_);

        // Initialize default position size
        // maxPositionBTC: 100 BTC = 10,000,000,000 satoshis
        // maxVaultsPerPosition: 10 vaults
        positionSizeParams = PositionSizeParams({
            maxPositionBTC: 10_000_000_000, // 100 BTC in satoshis
            maxVaultsPerPosition: 10
        });
    }

    // ═══════════════════════════════════════════════════════════════════════════
    //                            LLP ADMIN FUNCTIONS
    // ═══════════════════════════════════════════════════════════════════════════

    /// @notice Register a new Liquidation Liquidity Provider
    /// @param llp Address of the LLP contract
    /// @dev LLP is enabled by default upon registration. Must be a contract address
    ///      that implements ILiquidationLiquidityProvider. Validates interface support
    ///      via ERC-165.
    function registerLLP(address llp) external onlyAdmin {
        if (llp == address(0)) revert AdapterErrors.ZeroAddress();
        if (isRegisteredLLP[llp]) revert AdapterErrors.LLPAlreadyRegistered(llp);
        if (llp.code.length == 0) revert AdapterErrors.NotContract();

        // Validate ERC-165 interface support — reverts naturally on failure
        require(IERC165(llp).supportsInterface(type(ILiquidationLiquidityProvider).interfaceId));

        isRegisteredLLP[llp] = true;
        llpEnabled[llp] = true;

        emit AdapterEvents.LLPRegistered(llp);
    }

    /// @notice Toggle the enabled status of an LLP
    /// @param llp Address of the LLP to toggle
    /// @dev Does not deregister the LLP, only disables/enables it
    function toggleLLPEnabled(address llp) external onlyAdmin {
        if (!isRegisteredLLP[llp]) revert AdapterErrors.LLPNotRegistered(llp);

        bool newStatus = !llpEnabled[llp];
        llpEnabled[llp] = newStatus;

        emit AdapterEvents.LLPStatusChanged(llp, newStatus);
    }

    // ═══════════════════════════════════════════════════════════════════════════
    //                          RESOLVER ADMIN FUNCTIONS
    // ═══════════════════════════════════════════════════════════════════════════

    /// @notice Register a position resolver for the adapter
    /// @param resolver The resolver contract that maps depositors to position accounts
    /// @dev Validates the resolver implements IAaveAdapterPositionResolver by calling APPLICATION_ADAPTER()
    ///      and checking it returns a non-zero address. Reverts if already registered.
    function registerResolver(address resolver) external onlyAdmin {
        if (resolver == address(0)) revert AdapterErrors.ZeroAddress();
        if (resolver.code.length == 0) revert AdapterErrors.NotContract();
        if (isRegisteredResolver[resolver]) revert AdapterErrors.InvalidPositionResolver();

        // Validate resolver is configured for this adapter
        if (IAaveAdapterPositionResolver(resolver).APPLICATION_ADAPTER() != ADAPTER) {
            revert AdapterErrors.InvalidPositionResolver();
        }

        isRegisteredResolver[resolver] = true;
        emit AdapterEvents.AdapterPositionResolverAdded(resolver);
    }

    /// @notice Unregister a position resolver from the adapter
    /// @param resolver The resolver contract to unregister
    /// @dev Reverts unless the resolver is currently registered
    function removeResolver(address resolver) external onlyAdmin {
        if (!isRegisteredResolver[resolver]) {
            revert AdapterErrors.InvalidPositionResolver();
        }
        isRegisteredResolver[resolver] = false;
        emit AdapterEvents.AdapterPositionResolverRemoved(resolver);
    }

    // ═══════════════════════════════════════════════════════════════════════════
    //                      POSITION SIZE ADMIN FUNCTIONS
    // ═══════════════════════════════════════════════════════════════════════════

    /// @notice Set position size boundary parameters
    /// @dev Only callable by contract admin. Reverts if maxVaultsPerPosition is zero.
    /// @param params New position size parameters
    function setPositionSizeParams(PositionSizeParams calldata params) external onlyAdmin {
        if (params.maxVaultsPerPosition == 0) revert AdapterErrors.InvalidPositionSizes();
        positionSizeParams = params;
        emit PositionSizeParamsUpdated(params);
    }

    // ═══════════════════════════════════════════════════════════════════════════
    //                          VIEW FUNCTIONS
    // ═══════════════════════════════════════════════════════════════════════════

    /// @notice Get position size boundary parameters
    /// @return maxPositionBTC Maximum total BTC per position (in satoshis)
    /// @return maxVaultsPerPosition Maximum number of vaults per position
    function getPositionSizeParams() external view returns (uint256 maxPositionBTC, uint256 maxVaultsPerPosition) {
        PositionSizeParams memory params = positionSizeParams;
        return (params.maxPositionBTC, params.maxVaultsPerPosition);
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol

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

pragma solidity ^0.8.0;

import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

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

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with a standardized message including the required role.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     *
     * _Available since v4.1._
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    function __AccessControl_init() internal onlyInitializing {
    }

    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
    }

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

    /**
     * @dev Revert with a standard message if `_msgSender()` is missing `role`.
     * Overriding this function changes the behavior of the {onlyRole} modifier.
     *
     * Format of the revert message is described in {_checkRole}.
     *
     * _Available since v4.6._
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Revert with a standard message if `account` is missing `role`.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        StringsUpgradeable.toHexString(account),
                        " is missing role ",
                        StringsUpgradeable.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    /**
     * @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 override 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 override 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 override 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 `account`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address account) public virtual override {
        require(account == _msgSender(), "AccessControl: can only renounce roles for self");

        _revokeRole(role, account);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event. Note that unlike {grantRole}, this function doesn't perform any
     * checks on the calling account.
     *
     * May emit a {RoleGranted} event.
     *
     * [WARNING]
     * ====
     * This function should only be called from the constructor when setting
     * up the initial roles for the system.
     *
     * Using this function in any other way is effectively circumventing the admin
     * system imposed by {AccessControl}.
     * ====
     *
     * NOTE: This function is deprecated in favor of {_grantRole}.
     */
    function _setupRole(bytes32 role, address account) internal virtual {
        _grantRole(role, account);
    }

    /**
     * @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 Grants `role` to `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual {
        if (!hasRole(role, account)) {
            _roles[role].members[account] = true;
            emit RoleGranted(role, account, _msgSender());
        }
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual {
        if (hasRole(role, account)) {
            _roles[role].members[account] = false;
            emit RoleRevoked(role, account, _msgSender());
        }
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

lib/openzeppelin-contracts-upgradeable/contracts/access/IAccessControlUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControlUpgradeable {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    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, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    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 `account`.
     */
    function renounceRole(bytes32 role, address account) external;
}

lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;

import "../../utils/AddressUpgradeable.sol";

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     * @custom:oz-retyped-from bool
     */
    uint8 private _initialized;

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint8 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _initialized = 1;
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: setting the version to 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _initialized = version;
        _initializing = true;
        _;
        _initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized != type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint8) {
        return _initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _initializing;
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/AddressUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol

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

pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";

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

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

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

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/StringsUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/MathUpgradeable.sol";
import "./math/SignedMathUpgradeable.sol";

/**
 * @dev String operations.
 */
library StringsUpgradeable {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = MathUpgradeable.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toString(int256 value) internal pure returns (string memory) {
        return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMathUpgradeable.abs(value))));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, MathUpgradeable.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165Upgradeable.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 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);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
    function __ERC165_init() internal onlyInitializing {
    }

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165Upgradeable).interfaceId;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/IERC165Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165Upgradeable {
    /**
     * @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[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/math/MathUpgradeable.sol

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

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library MathUpgradeable {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

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

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return 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) {
        // (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 up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev 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 {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 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 prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

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

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, 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.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

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

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            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^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // 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^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice 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) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice 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 + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

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

    /**
     * @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 + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * 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 + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * 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 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @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 + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
        }
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/math/SignedMathUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMathUpgradeable {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

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

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol

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

pragma solidity >=0.4.11;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 */
interface IERC1967 {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);
}

lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol

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

pragma solidity >=0.4.16;

/**
 * @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol

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

pragma solidity ^0.8.21;

import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";

/**
 * @dev This library provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
 */
library ERC1967Utils {
    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @dev Returns the current implementation address.
     */
    function getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit IERC1967.Upgraded(newImplementation);

        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        if (newAdmin == address(0)) {
            revert ERC1967InvalidAdmin(address(0));
        }
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {IERC1967-AdminChanged} event.
     */
    function changeAdmin(address newAdmin) internal {
        emit IERC1967.AdminChanged(getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the ERC-1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        if (newBeacon.code.length == 0) {
            revert ERC1967InvalidBeacon(newBeacon);
        }

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit IERC1967.BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}

lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol

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

pragma solidity >=0.4.16;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {UpgradeableBeacon} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.22;

import {IERC1822Proxiable} from "../../interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 *
 * @custom:stateless
 */
abstract contract UUPSUpgradeable is IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

    /**
     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view notDelegated returns (bytes32) {
        return ERC1967Utils.IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC-1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }
        if (LowLevelCall.callNoReturn(recipient, amount, "")) {
            // call successful, nothing to do
            return;
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        bool success = LowLevelCall.callNoReturn(target, value, data);
        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
            return LowLevelCall.returnData();
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        bool success = LowLevelCall.staticcallNoReturn(target, data);
        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
            return LowLevelCall.returnData();
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        bool success = LowLevelCall.delegatecallNoReturn(target, data);
        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
            return LowLevelCall.returnData();
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     *
     * NOTE: This function is DEPRECATED and may be removed in the next major release.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        // only check if target is a contract if the call was successful and the return data is empty
        // otherwise we already know that it was a contract
        if (success && (returndata.length > 0 || target.code.length > 0)) {
            return returndata;
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (returndata.length > 0) {
            LowLevelCall.bubbleRevert(returndata);
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else if (returndata.length > 0) {
            LowLevelCall.bubbleRevert(returndata);
        } else {
            revert Errors.FailedCall();
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/Errors.sol

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

pragma solidity ^0.8.20;

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

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

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

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

lib/openzeppelin-contracts/contracts/utils/LowLevelCall.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Library of low level call functions that implement different calling strategies to deal with the return data.
 *
 * WARNING: Using this library requires an advanced understanding of Solidity and how the EVM works. It is recommended
 * to use the {Address} library instead.
 */
library LowLevelCall {
    /// @dev Performs a Solidity function call using a low level `call` and ignoring the return data.
    function callNoReturn(address target, bytes memory data) internal returns (bool success) {
        return callNoReturn(target, 0, data);
    }

    /// @dev Same as {callNoReturn}, but allows to specify the value to be sent in the call.
    function callNoReturn(address target, uint256 value, bytes memory data) internal returns (bool success) {
        assembly ("memory-safe") {
            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `call` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function callReturn64Bytes(
        address target,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        return callReturn64Bytes(target, 0, data);
    }

    /// @dev Same as {callReturnBytes32Pair}, but allows to specify the value to be sent in the call.
    function callReturn64Bytes(
        address target,
        uint256 value,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Performs a Solidity function call using a low level `staticcall` and ignoring the return data.
    function staticcallNoReturn(address target, bytes memory data) internal view returns (bool success) {
        assembly ("memory-safe") {
            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `staticcall` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function staticcallReturn64Bytes(
        address target,
        bytes memory data
    ) internal view returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Performs a Solidity function call using a low level `delegatecall` and ignoring the return data.
    function delegatecallNoReturn(address target, bytes memory data) internal returns (bool success) {
        assembly ("memory-safe") {
            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `delegatecall` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function delegatecallReturn64Bytes(
        address target,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Returns the size of the return data buffer.
    function returnDataSize() internal pure returns (uint256 size) {
        assembly ("memory-safe") {
            size := returndatasize()
        }
    }

    /// @dev Returns a buffer containing the return data from the last call.
    function returnData() internal pure returns (bytes memory result) {
        assembly ("memory-safe") {
            result := mload(0x40)
            mstore(result, returndatasize())
            returndatacopy(add(result, 0x20), 0x00, returndatasize())
            mstore(0x40, add(result, add(0x20, returndatasize())))
        }
    }

    /// @dev Revert with the return data from the last call.
    function bubbleRevert() internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            returndatacopy(fmp, 0x00, returndatasize())
            revert(fmp, returndatasize())
        }
    }

    function bubbleRevert(bytes memory returndata) internal pure {
        assembly ("memory-safe") {
            revert(add(returndata, 0x20), mload(returndata))
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

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

src/applications/aave/abstract/AaveAdapterTemplateUpg.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.28;

import {TBVTemplateUpg} from "../../../utility/TBVTemplateUpg.sol";

/// @title AaveAdapterTemplateUpg
/// @notice Application-level role IDs for the TBV governance template
abstract contract AaveAdapterTemplateUpg is TBVTemplateUpg {
    function _ADMIN_ROLE() internal pure override returns (bytes32) {
        return keccak256("APPLICATION_ADMIN");
    }

    function _PAUSE_GUARDIAN_ROLE() internal pure override returns (bytes32) {
        return keccak256("APPLICATION_PAUSE_GUARDIAN");
    }

    function _FREEZE_GUARDIAN_ROLE() internal pure override returns (bytes32) {
        return keccak256("APPLICATION_FREEZE_GUARDIAN");
    }
}

src/applications/aave/interfaces/IAaveAdapterConfig.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

/// @title IAaveAdapterConfig
/// @notice Interface for the unified Aave Adapter Config managing LLPs, Resolvers, and position size parameters
interface IAaveAdapterConfig {
    // ═══════════════════════════════════════════════════════════════════════════
    //                          TYPES
    // ═══════════════════════════════════════════════════════════════════════════

    /// @notice Position size boundary parameters
    struct PositionSizeParams {
        /// @notice Maximum total BTC per position (in satoshis)
        uint256 maxPositionBTC;
        /// @notice Maximum number of vaults per position. Must be non-zero.
        uint256 maxVaultsPerPosition;
    }

    // ═══════════════════════════════════════════════════════════════════════════
    //                          EVENTS
    // ═══════════════════════════════════════════════════════════════════════════

    /// @notice Event emitted when position size boundary parameters are updated
    /// @param newParams The new position size parameters
    event PositionSizeParamsUpdated(PositionSizeParams newParams);

    // ═══════════════════════════════════════════════════════════════════════════
    //                          IMMUTABLES
    // ═══════════════════════════════════════════════════════════════════════════

    /// @notice The adapter address that resolvers must be configured for
    function ADAPTER() external view returns (address);

    // ═══════════════════════════════════════════════════════════════════════════
    //                          LLP FUNCTIONS
    // ═══════════════════════════════════════════════════════════════════════════

    /// @notice Register a new Liquidation Liquidity Provider
    /// @param llp Address of the LLP contract
    function registerLLP(address llp) external;

    /// @notice Toggle the enabled status of an LLP
    /// @param llp Address of the LLP to toggle
    function toggleLLPEnabled(address llp) external;

    /// @notice Check if an LLP is registered
    /// @param llp Address of the LLP to check
    /// @return True if the LLP is registered
    function isRegisteredLLP(address llp) external view returns (bool);

    /// @notice Check if an LLP is enabled
    /// @param llp Address of the LLP to check
    /// @return True if the LLP is enabled
    function llpEnabled(address llp) external view returns (bool);

    // ═══════════════════════════════════════════════════════════════════════════
    //                          RESOLVER FUNCTIONS
    // ═══════════════════════════════════════════════════════════════════════════

    /// @notice Register a position resolver for the adapter
    /// @param resolver The resolver contract that maps depositors to position accounts
    function registerResolver(address resolver) external;

    /// @notice Unregister a position resolver from the adapter
    /// @param resolver The resolver contract to unregister
    function removeResolver(address resolver) external;

    /// @notice Check if a resolver is registered
    /// @param resolver Address of the resolver to check
    /// @return True if the resolver is registered
    function isRegisteredResolver(address resolver) external view returns (bool);

    // ═══════════════════════════════════════════════════════════════════════════
    //                      POSITION SIZE FUNCTIONS
    // ═══════════════════════════════════════════════════════════════════════════

    /// @notice Set position size boundary parameters
    /// @dev Reverts if maxVaultsPerPosition is zero.
    /// @param params New position size parameters
    function setPositionSizeParams(PositionSizeParams calldata params) external;

    /// @notice Get position size boundary parameters
    /// @return maxPositionBTC Maximum total BTC per position (in satoshis)
    /// @return maxVaultsPerPosition Maximum number of vaults per position
    function getPositionSizeParams() external view returns (uint256 maxPositionBTC, uint256 maxVaultsPerPosition);
}

src/applications/aave/interfaces/IAaveAdapterPositionResolver.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.28;

/// @title IAaveAdapterPositionResolver
/// @notice Interface for resolver contracts that map depositors to application position accounts
interface IAaveAdapterPositionResolver {
    /// @notice Get the address of the application adapter contract
    /// @return The address of the application adapter contract
    function APPLICATION_ADAPTER() external view returns (address);

    /// @notice Get the position account associated with a given user ethereum address and metadata payload
    /// @param user The Ethereum address of the user for whom to resolve the position account
    /// @param metadata An arbitrary metadata payload used by the resolver to determine the position account
    /// @return positionAccount The address of the position account associated with the vault
    function getPositionAccount(address user, bytes memory metadata) external view returns (address positionAccount);

    /// @notice Callback function that the Application Adapter calls to notify the resolver of vault activations
    /// @param user The Ethereum address of the user for whom the vault was activated
    /// @param positionAccount The address of the position account associated with the activated vault
    /// @param vaultId The unique identifier of the activated vault
    function notifyVaultActivation(address user, address positionAccount, bytes32 vaultId) external;
}

src/applications/aave/interfaces/ILiquidationLiquidityProvider.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.28;

import {TokenAmountLib} from "../lib/types/TokenAmountLib.sol";

/// @title ILiquidationLiquidityProvider
/// @notice Interface for liquidation settlement with multi-token payout support.
///         The adapter transfers ownership of the seized vault to the
///         LLP before calling settleLiquidation. The LLP pays the
///         liquidator in one or more tokens and handles vault redemption
///         on its own schedule. Each liquidation settles exactly one vault.
interface ILiquidationLiquidityProvider {
    /// @notice Get the list of tokens this LLP can use for settlement payouts
    /// @return tokens Array of ERC20 token addresses used for payouts (e.g., [exitBTC or WBTC, USDC])
    function getSettlementTokens() external view returns (address[] memory tokens);

    /// @notice Check if a token is supported for settlement by this LLP
    /// @param token Token address to check
    /// @return isSupported True if the token is supported for settlement
    function isSettlementToken(address token) external view returns (bool isSupported);

    /// @notice Settle a liquidation by paying the liquidator
    ///         and taking ownership of seized vaults.
    /// @dev Called by the adapter after vault ownership has
    ///      been assigned to this LLP. The liquidator implicitly
    ///      trusts the LLP's returned settlement amounts by choosing
    ///      to use that LLP for the liquidation. If this call reverts,
    ///      the entire liquidation tx reverts (vault ownership changes
    ///      are undone).
    ///      MUST NOT call adapter.redeemVaultFromLLP()
    ///      during this call. The adapter's reentrancy
    ///      guard is held. Vault redemption must happen
    ///      in a separate transaction.
    ///      The LLP can fetch the vault amount from the BTCVaultRegistry
    ///      using the provided vaultId.
    ///
    ///      requestedTokens validation: The LLP MUST validate that:
    ///      1. All requested tokens are supported (revert with UnsupportedSettlementToken if not)
    ///      2. Payout meets or exceeds requested minimum amounts (revert with InsufficientSettlementAmount if not)
    ///      The adapter does not validate requestedTokens - this is the LLP's responsibility.
    /// @param liquidator Address to receive the settlement payout
    /// @param borrower The liquidated borrower
    /// @param vaultId The seized vault, already owned by this LLP when this is called
    /// @param requestedTokens Tokens and minimum amounts requested by the liquidator. An empty array
    ///        means the liquidator accepts any supported token. The LLP must validate and honor these.
    /// @return payouts Tokens and amounts paid to the liquidator
    function settleLiquidation(
        address liquidator,
        address borrower,
        bytes32 vaultId,
        TokenAmountLib.TokenAmount[] calldata requestedTokens
    ) external returns (TokenAmountLib.TokenAmount[] memory payouts);
}

src/applications/aave/lib/types/Errors.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

library Errors {
    /// @notice Error thrown when zero address is provided where not allowed
    error ZeroAddress();

    /// @notice Error thrown when zero amount is provided
    error ZeroAmount();

    /// @notice Error thrown when caller is not authorized
    error Unauthorized();

    /// @notice Error thrown when invalid amount is provided
    error InvalidAmount();

    /// @notice Error thrown when caller is not the configured adapter
    error OnlyAdapter();

    /// @notice Error thrown when a BTC vault has an invalid usage status
    error InvalidBTCVaultUsageStatus();

    /// @notice Error thrown when address is not a contract
    error NotContract();

    /// @notice Error thrown when a token transfer targets an unauthorized destination
    error UnauthorizedTransferDestination();

    /// @notice Error thrown when input array length is zero
    error EmptyArray();

    /// @notice Error thrown when invalid proxy contract is provided
    error InvalidProxyContract();

    /// @notice Error thrown when withdrawal did not recall the full vault amount
    /// @param expected The expected vault amount to be withdrawn
    /// @param actual The actual amount withdrawn
    error IncompleteWithdrawal(uint256 expected, uint256 actual);

    /// @notice Error thrown when a position resolver is invalid for the target application
    error InvalidPositionResolver();

    /// @notice Error thrown when spoke oracle returns zero price for a required reserve
    error InvalidOraclePrice();

    /// @notice Error thrown when a position does not satisfy Aave liquidation conditions
    error PositionNotLiquidatable();

    /// @notice Error thrown when collateral is left over on the proxy while debt remains outstanding, so no
    ///         fairness payment can be settled for the excess
    error InvalidPostLiquidationState();

    /// @notice Error thrown when LLP address is not registered
    /// @param llp The unregistered LLP address
    error LLPNotRegistered(address llp);

    /// @notice Error thrown when attempting to register an LLP that is already registered
    /// @param llp The already-registered LLP address
    error LLPAlreadyRegistered(address llp);

    /// @notice Error thrown when LLP is disabled for new settlements
    error LLPDisabled();

    /// @notice Error thrown when position sizes are invalid (e.g., exceeding number of vaults or total amount)
    error InvalidPositionSizes();

    /// @notice Error thrown when a vault removal request contains missing or invalid vaults
    error InvalidVaultsArray();

    /// @notice Error thrown when the configured proxy implementation is invalid
    error InvalidImplementation();

    /// @notice Error thrown when activationMetadata specifies an unsupported version
    error InvalidActivationMetadataVersion();

    /// @notice Error thrown when a delegated position account already exists for a user and delegatee pair
    error PositionAccountAlreadyExists();

    /// @notice Error thrown when deployment of a delegated position account fails
    error PositionAccountCreationFailed();

    /// @notice Error thrown when no delegated position account exists for a user and delegatee pair
    error PositionAccountDoesNotExist();

    /// @notice Error thrown when a delegated borrow exceeds the remaining reserve allowance
    error InsufficientBorrowAllowance();

    /// @notice Error thrown when a delegated borrow specifies an invalid receiver
    error InvalidReceiver();

    /// @notice Error thrown when position account creation or borrowing uses an unverified delegatee
    error DelegateeNotVerified();

    /// @notice Error thrown when a curator that the resolver has not approved is appointed or borrows
    error CuratorNotApproved();

    /// @notice Error thrown when a depositor outside an enabled resolver allowlist creates or activates a position
    error DepositorNotAllowed();

    /// @notice Error thrown when a curator borrow leaves the position below the resolver's minimum health factor
    /// @param healthFactor Position health factor after the borrow, in WAD
    /// @param minimum Minimum health factor the resolver requires after a curator borrow, in WAD
    error BorrowHealthFactorTooLow(uint256 healthFactor, uint256 minimum);

    /// @notice Error thrown when a minimum borrow health factor does not exceed the liquidation threshold
    error InvalidMinBorrowHealthFactor();

    /// @notice Error thrown when a resolver's ERC4626 yield vault does not take its debt reserve's underlying token
    error YieldVaultAssetMismatch();

    /// @notice Error thrown when a resolver's ERC4626 yield vault has fewer shares than the resolver's minimum supply
    error YieldVaultSupplyTooLow();

    /// @notice Error thrown when a curator borrow's yield vault deposit mints fewer shares than the owner's
    ///         minimum deposit rate requires
    /// @param assets Amount of the underlying token deposited
    /// @param shares Yield vault shares the deposit minted
    error YieldVaultDepositRateTooLow(uint256 assets, uint256 shares);

    /// @notice Error thrown when a curator repay's yield vault withdrawal burns more shares than the owner's
    ///         maximum withdraw rate allows
    /// @param assets Amount of the underlying token withdrawn
    /// @param shares Yield vault shares the withdrawal burned
    error YieldVaultWithdrawRateTooHigh(uint256 assets, uint256 shares);

    /// @notice Error thrown when a yield vault deposit or withdrawal reports a share count that the position
    ///         account's share balance change does not back: fewer shares received or more shares burned
    /// @param reportedShares Shares the yield vault call returned
    /// @param balanceChange Shares the account's balance actually gained (deposit) or lost (withdrawal)
    error YieldVaultShareBalanceMismatch(uint256 reportedShares, uint256 balanceChange);

    /// @notice Error thrown when a curator borrows before the owner has set the yield vault rates
    error YieldVaultRatesNotSet();

    /// @notice Error thrown when the owner sets a zero yield vault rate
    error InvalidYieldVaultRates();

    /// @notice Error thrown when a resolver is configured with a debt reserve ID that is out of range or is the
    ///         vaultBTC reserve
    error InvalidReserveId();

    /// @notice Error thrown when the Hub's vBTC added shares and added assets diverge, breaking the 1:1 assumption
    ///         that liquidation collateral accounting relies on
    error VaultBTCSharesAssetsMismatch();

    /// @notice Error thrown when the exitBTC a liquidation charges the liquidator exceeds the cap they supplied
    error ExcessiveExitBtcPayment();

    /// @notice Error thrown when a liquidation targets a borrower holding no collateralized vaults
    error NoCollateralizedVaults();

    /// @notice Error thrown when a resolved position account does not report the expected resolver
    error InvalidPositionAccount();

    /// @notice Error thrown when a borrower attempts to reorder vaults on a liquidatable position
    error PositionNotHealthy();

    /// @notice Error thrown when the adapter is initialized behind a proxy whose address is not the Core Spoke's
    ///         immutable `LIQUIDATION_MANAGER`, which would leave every liquidation call rejected by the Spoke
    error SpokeLiquidationManagerNotSetProperly();
}

src/applications/aave/lib/types/Events.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

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

library Events {
    /// @notice Event emitted when a proxy is added to the valid list
    event ProxyAdded(address indexed proxy);

    /// @notice Emitted when the recipient of liquidation fees and failed fairness payments is updated
    event AdapterApplicationRecipientUpdated(address applicationFeeRecipient);

    /// @notice Emitted when the borrower interest fee recipient is updated
    event AdapterInterestFeeRecipientUpdated(address interestFeeRecipient);

    /// @notice Emitted when the liquidation fee is updated
    event AdapterLiquidationFeeUpdated(uint256 liquidationFeeBps);

    /// @notice Emitted when a position resolver is registered on the adapter
    /// @param positionResolver The resolver contract that can map depositors to position accounts
    event AdapterPositionResolverAdded(address indexed positionResolver);

    /// @notice Emitted when a position resolver is removed from the adapter
    /// @param positionResolver The resolver contract that was removed
    event AdapterPositionResolverRemoved(address indexed positionResolver);

    /// @notice Emitted when collateral is added to a position
    /// @param positionAccount The positionAccount address
    /// @param vaultId The vault id of the collateral added
    event CollateralAdded(address indexed positionAccount, bytes32 indexed vaultId);

    /// @notice Emitted when assets are borrowed from a position
    /// @param borrower The borrower address
    /// @param debtReserveId Borrowed reserve identifier
    /// @param receiver The receiver of the borrowed assets
    /// @param borrowAmount Amount of assets borrowed
    event BorrowedFromPosition(
        address indexed borrower, uint256 indexed debtReserveId, address indexed receiver, uint256 borrowAmount
    );

    /// @notice Emitted when debt is repaid from a position
    /// @param borrower The borrower repaying the debt
    /// @param debtReserveId Debt reserve identifier
    /// @param repayAmount Amount of assets repaid
    event RepaidFromPosition(address indexed borrower, uint256 indexed debtReserveId, uint256 repayAmount);

    /// @notice Event emitted when the core spoke proxy implementation is updated
    /// @param newImpl The new implementation address
    event CoreSpokeProxyImplUpdated(address indexed newImpl);

    /// @notice Event emitted when a proxy is deployed for a user
    /// @param user The user for whom the proxy is deployed
    /// @param proxy The address of the deployed proxy
    event ProxyDeployed(address indexed user, address indexed proxy);

    /// @notice Event emitted when a new user proxy is created
    /// @param user The user for whom the proxy is created
    /// @param proxy The address of the newly created proxy
    event UserProxyCreated(address indexed user, address indexed proxy);

    /// @notice Event emitted when all collateral is withdrawn from a position
    /// @param positionAccount The positionAccount address
    /// @param vaultId The vault id of the collateral withdrawn
    event CollateralWithdrawn(address indexed positionAccount, bytes32 indexed vaultId);

    /// @notice Event emitted when vault ownership is changed
    /// @param vaultId The vault identifier
    /// @param newOwner The new owner address
    event VaultOwnershipChanged(bytes32 indexed vaultId, address indexed newOwner);

    /// @notice Event emitted when fairness payment is transferred from liquidator to depositor
    /// @param positionAccount The positionAccount receiving the payment
    /// @param liquidator The liquidator paying the fairness amount
    /// @param amount The amount transferred in the configured fairness payment token
    event FairnessPaymentPaid(address indexed positionAccount, address indexed liquidator, uint256 amount);

    /// @notice Event emitted when fairness payment transfer fails
    /// @param positionAccount The positionAccount that should have received the payment
    /// @param liquidator The liquidator who attempted to pay
    /// @param protocolRecipient The protocol fee recipient
    /// @param amount The amount that failed to transfer
    event FairnessPaymentFailed(
        address indexed positionAccount, address indexed liquidator, address protocolRecipient, uint256 amount
    );

    /// @notice Event emitted when a user's collateralized vaults are reordered
    /// @param borrower The borrower whose vaults were reordered
    /// @param newVaults The new order of vault IDs after reordering
    event VaultsReordered(address indexed borrower, bytes32[] newVaults);

    /// @notice Event emitted when interest fee basis points are updated
    /// @param newInterestFeeBps The new interest fee in basis points
    event InterestFeeUpdated(uint256 newInterestFeeBps);

    /// @notice Event emitted when an LLP is registered
    /// @param llp The LLP contract address
    event LLPRegistered(address indexed llp);

    /// @notice Event emitted when an LLP's enabled status changes
    /// @param llp The LLP address
    /// @param enabled Whether the LLP is now enabled
    event LLPStatusChanged(address indexed llp, bool enabled);

    /// @notice Event emitted when vaults are settled via an LLP
    /// @param llp The LLP address used for settlement
    /// @param liquidator The liquidator receiving settlement
    /// @param borrower The liquidated borrower
    /// @param vaultId The seized vault transferred to the LLP
    event LiquidationSettledViaLLP(
        address indexed llp, address indexed liquidator, address indexed borrower, bytes32 vaultId
    );

    /// @notice Event emitted when the liquidation fee is collected during a liquidation
    /// @param token The address of the token in which the fee was collected
    /// @param amount The amount of the fee collected
    event LiquidationFeeCollected(address indexed token, uint256 amount);

    /// @notice Event emitted when the interest fee is collected during a repayment
    /// @param token The address of the token in which the fee was collected
    /// @param borrower The address of the borrower who paid the fee
    /// @param amount The amount of the fee collected
    event InterestFeeCollected(address indexed token, address indexed borrower, uint256 amount);

    /// @notice Emitted when a position account is bound to its resolver during its first resolver-based activation
    /// @dev Emitted once per position account; the binding is never cleared or rewritten
    /// @param resolver The registered resolver the position account is bound to
    /// @param positionAccount The position account that was bound
    event ResolverPositionAccountBound(address indexed resolver, address indexed positionAccount);

    /// @notice Event emitted for each vault liquidated in a BTCVaultCoreSpoke liquidation
    /// @param proxyContract The liquidated borrower's position proxy
    /// @param vaultId The vault ID that was liquidated
    /// @param debtReserveId Spoke reserve ID of the debt that was repaid
    /// @param liquidator The liquidator that executed the liquidation call
    /// @param amountDebtTokenConsumed Debt token the Spoke consumed; unspent input was refunded
    /// @param amountCollateralSeized VaultBTC seized, always the vault's full BTC amount
    /// @param liquidationBonus Bonus the Spoke applied, in BPS where 100_00 is no bonus
    /// @param liquidationFee Liquidation fee owed to the application recipient
    /// @param fairnessPayment Fairness payment owed to the borrower; zero amount if the Spoke seized the
    ///        full vault
    event VaultLiquidated(
        address indexed proxyContract,
        bytes32 indexed vaultId,
        uint256 indexed debtReserveId,
        address liquidator,
        uint256 amountDebtTokenConsumed,
        uint256 amountCollateralSeized,
        uint256 liquidationBonus,
        TokenAmountLib.TokenAmount liquidationFee,
        TokenAmountLib.TokenAmount fairnessPayment
    );
}

src/applications/aave/lib/types/TokenAmountLib.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

/**
 * @title TokenAmountLib
 * @notice Library providing the TokenAmount struct for internal debt snapshots, and the
 *         accumulator used to collapse per-reserve amounts into per-token totals
 */
library TokenAmountLib {
    /// @notice Represents a token address paired with an amount
    /// @param token The ERC-20 token address
    /// @param amount The token amount (in the token's native decimals)
    struct TokenAmount {
        address token;
        uint256 amount;
    }

    /// @notice Accumulate `amount` under `token`, merging into the existing entry when present
    /// @dev Appends at the end, so entries stay in first-appearance order. Callers must use the
    ///      returned array: the append path allocates a new one, while the merge path returns `arr`
    ///      itself. `arr` is never left stale, but it is not left untouched either — both paths
    ///      write through to the caller's structs, since memory-to-memory struct assignment copies
    ///      the pointer rather than the value. Reassign in place (`x = x.add(...)`) and do not keep
    ///      a second reference to `arr` expecting it to hold the pre-call amounts.
    ///      Each new token reallocates and copies, so this is quadratic in the number of distinct
    ///      tokens; it is sized for the handful of reserves one liquidation selects.
    /// @param arr Entries accumulated so far
    /// @param token The ERC-20 token to accumulate under
    /// @param amount Amount to add to that token's running total
    /// @return The accumulated entries, including `token`
    function add(TokenAmount[] memory arr, address token, uint256 amount) internal pure returns (TokenAmount[] memory) {
        for (uint256 i = 0; i < arr.length; ++i) {
            if (arr[i].token == token) {
                arr[i].amount += amount;
                return arr;
            }
        }

        TokenAmount[] memory result = new TokenAmount[](arr.length + 1);
        for (uint256 i = 0; i < arr.length; ++i) {
            result[i] = arr[i];
        }
        result[result.length - 1] = TokenAmount({token: token, amount: amount});
        return result;
    }
}

src/interfaces/ITBVPausable.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

interface ITBVPausable {
    enum PauseState {
        None,
        Frozen,
        Paused
    }
}

src/utility/TBVAccessControlUpg.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.28;

import "../../lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol";
import "./types/Errors.sol";

abstract contract TBVAccessControlUpg is AccessControlUpgradeable {
    modifier onlyAdmin() {
        require(hasRole(_ADMIN_ROLE(), msg.sender), Errors.TBV_Unauthorized());
        _;
    }

    function _ADMIN_ROLE() internal pure virtual returns (bytes32);

    function _PAUSE_GUARDIAN_ROLE() internal pure virtual returns (bytes32);

    function _FREEZE_GUARDIAN_ROLE() internal pure virtual returns (bytes32);

    function __TBVAccessControlUpg_init(address _initialAdmin) internal onlyInitializing {
        __AccessControl_init();
        _grantRole(DEFAULT_ADMIN_ROLE, _initialAdmin);
        _grantRole(_ADMIN_ROLE(), _initialAdmin);
        _setRoleAdmin(_PAUSE_GUARDIAN_ROLE(), _ADMIN_ROLE());
        _setRoleAdmin(_FREEZE_GUARDIAN_ROLE(), _ADMIN_ROLE());
    }
}

src/utility/TBVPausableUpg.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.28;

import {Initializable} from "../../lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol";
import {ITBVPausable} from "../interfaces/ITBVPausable.sol";
import {Errors} from "./types/Errors.sol";

/**
 * @notice Cases to notice:
 * - If the contract is paused, freeze role could not change it to freeze state
 * - Unpause should be equivalently sensitive compared to pause
 */
abstract contract TBVPausableUpg is Initializable, ITBVPausable {
    event Paused(address indexed pauser);
    event Frozen(address indexed freezer);
    event Unpaused(address indexed pauser);
    event Unfrozen(address indexed unfreezer);

    PauseState public pauseState;
    uint256[50] private __gap;

    function __TBVPausableUpg_init() internal onlyInitializing {
        pauseState = PauseState.Frozen;
    }

    modifier whenNotFrozen() {
        _whenNotFrozen();
        _;
    }

    modifier whenNotPaused() {
        _whenNotPaused();
        _;
    }

    function _whenNotFrozen() internal view {
        PauseState currentState = pauseState;
        if (currentState == PauseState.Frozen) revert Errors.TBV_Frozen();
        if (currentState == PauseState.Paused) revert Errors.TBV_Paused();
    }

    function _whenNotPaused() internal view {
        if (pauseState == PauseState.Paused) revert Errors.TBV_Paused();
    }

    function unpause() external virtual allowedToUnpause {
        PauseState currentState = pauseState;
        if (currentState == PauseState.Frozen) revert Errors.TBV_CannotUnpauseWhileFrozen();
        if (currentState != PauseState.Paused) revert Errors.TBV_NotPaused();
        pauseState = PauseState.None;
        emit Unpaused(msg.sender);
    }

    function freeze() external virtual allowedToFreeze {
        PauseState currentState = pauseState;
        if (currentState == PauseState.Frozen) revert Errors.TBV_AlreadyFrozen();
        if (currentState == PauseState.Paused) revert Errors.TBV_AlreadyPaused();
        pauseState = PauseState.Frozen;
        emit Frozen(msg.sender);
    }

    function unfreeze() external virtual allowedToUnfreeze {
        PauseState currentState = pauseState;
        if (currentState == PauseState.Paused) revert Errors.TBV_CannotUnfreezeWhilePaused();
        if (currentState != PauseState.Frozen) revert Errors.TBV_NotFrozen();
        pauseState = PauseState.None;
        emit Unfrozen(msg.sender);
    }

    function pause() external virtual allowedToPause {
        PauseState currentState = pauseState;
        if (currentState == PauseState.Paused) revert Errors.TBV_AlreadyPaused();
        pauseState = PauseState.Paused;
        emit Paused(msg.sender);
    }

    modifier allowedToFreeze() virtual;
    modifier allowedToPause() virtual;
    modifier allowedToUnpause() virtual;
    modifier allowedToUnfreeze() virtual;
}

src/utility/TBVTemplateUpg.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.28;

import {TBVAccessControlUpg} from "./TBVAccessControlUpg.sol";
import {TBVPausableUpg} from "./TBVPausableUpg.sol";
import {UUPSUpgradeable} from "../../lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol";
import {Errors} from "./types/Errors.sol";

/// @title TBVTemplateUpg
/// @notice Shared governance base: access control + pausability + UUPS upgradeability.
///         Protocol and application contracts inherit a thin role-ID layer on top of this.
abstract contract TBVTemplateUpg is TBVAccessControlUpg, TBVPausableUpg, UUPSUpgradeable {
    modifier allowedToFreeze() virtual override {
        // freeze: ADMIN or FREEZE_GUARDIAN
        require(
            hasRole(_ADMIN_ROLE(), msg.sender) || hasRole(_FREEZE_GUARDIAN_ROLE(), msg.sender),
            Errors.TBV_Unauthorized()
        );
        _;
    }

    modifier allowedToPause() virtual override {
        // pause: ADMIN or PAUSE_GUARDIAN
        require(
            hasRole(_ADMIN_ROLE(), msg.sender) || hasRole(_PAUSE_GUARDIAN_ROLE(), msg.sender), Errors.TBV_Unauthorized()
        );
        _;
    }

    modifier allowedToUnpause() virtual override {
        // unpause: ADMIN or PAUSE_GUARDIAN
        require(
            hasRole(_ADMIN_ROLE(), msg.sender) || hasRole(_PAUSE_GUARDIAN_ROLE(), msg.sender), Errors.TBV_Unauthorized()
        );
        _;
    }

    modifier allowedToUnfreeze() virtual override {
        // unfreeze: ADMIN or PAUSE_GUARDIAN
        require(
            hasRole(_ADMIN_ROLE(), msg.sender) || hasRole(_PAUSE_GUARDIAN_ROLE(), msg.sender), Errors.TBV_Unauthorized()
        );
        _;
    }

    /// @notice Authorize contract upgrade — only ADMIN
    function _authorizeUpgrade(address newImplementation) internal override onlyAdmin {}

    function __TBVTemplateUpg_init(address _initialAdmin) internal onlyInitializing {
        __TBVAccessControlUpg_init(_initialAdmin);
        __TBVPausableUpg_init();
    }

    uint256[50] private __gap;
}

src/utility/types/Errors.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

library Errors {
    // =============================================================================
    //                              COMMON VALIDATION ERRORS
    // =============================================================================

    /// @notice Error thrown when zero address is provided where not allowed
    error ZeroAddress();

    /// @notice Error thrown when caller is not authorized
    error Unauthorized();

    // =============================================================================
    //                              TBV COMMON ERRORS
    // =============================================================================

    /// @notice Error thrown when the contract is full-paused
    error TBV_Paused();

    /// @notice Error thrown when the contract is frozen
    error TBV_Frozen();

    /// @notice Error thrown when attempting to unpause a contract that is not full-paused
    error TBV_NotPaused();

    /// @notice Error thrown when attempting to unfreeze a contract that is not frozen
    error TBV_NotFrozen();

    /// @notice Error thrown when attempting to full-pause a contract that is already full-paused
    error TBV_AlreadyPaused();

    /// @notice Error thrown when attempting to freeze a contract that is already frozen
    error TBV_AlreadyFrozen();

    /// @notice Error thrown when attempting to unfreeze while the contract is paused
    error TBV_CannotUnfreezeWhilePaused();

    /// @notice Error thrown when attempting to unpause while the contract is frozen
    error TBV_CannotUnpauseWhileFrozen();

    /// @notice Error thrown when caller does not have the required TBV role
    error TBV_Unauthorized();
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    ":@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    ":@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    ":aave-v4/=lib/aave-v4/src/",
    ":elliptic-curve-solidity/=lib/elliptic-curve-solidity/",
    ":erc4626-tests/=lib/aave-v4/lib/erc4626-tests/",
    ":forge-std/=lib/forge-std/src/",
    ":openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    ":openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/",
    ":src/access/=lib/aave-v4/src/access/",
    ":src/config-engine/=lib/aave-v4/src/config-engine/",
    ":src/dependencies/=lib/aave-v4/src/dependencies/",
    ":src/deployments/=lib/aave-v4/src/deployments/",
    ":src/hub/=lib/aave-v4/src/hub/",
    ":src/interfaces/IExtSload.sol=lib/aave-v4/src/interfaces/IExtSload.sol",
    ":src/interfaces/IIntentConsumer.sol=lib/aave-v4/src/interfaces/IIntentConsumer.sol",
    ":src/interfaces/IMulticall.sol=lib/aave-v4/src/interfaces/IMulticall.sol",
    ":src/interfaces/INoncesKeyed.sol=lib/aave-v4/src/interfaces/INoncesKeyed.sol",
    ":src/interfaces/IRescuable.sol=lib/aave-v4/src/interfaces/IRescuable.sol",
    ":src/libraries/=lib/aave-v4/src/libraries/",
    ":src/position-manager/=lib/aave-v4/src/position-manager/",
    ":src/spoke/=lib/aave-v4/src/spoke/",
    ":src/utils/=lib/aave-v4/src/utils/",
    ":vault-contracts/=src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.