Skip to content
Verified contractExactBUSL-1.1

SpokeUnderlyingManagerInstance

Address0x2faadf60682a0edc4b19a980543864f60ea4a7d3
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.30

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
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,391,879
Creation transaction
0xc1d4932180…66b664de70

33 files

src/protocol/underlyingManager/SpokeUnderlyingManagerInstance.sol

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

import {SpokeUnderlyingManager} from "./SpokeUnderlyingManager.sol";
import {ISpokeUnderlyingManager} from "./interfaces/ISpokeUnderlyingManager.sol";

/**
 * @title SpokeUnderlyingManagerInstance
 * @author Clovis Protocol
 * @notice Deployable instance of SpokeUnderlyingManager
 */
/// @dev Aave-style proxy lockout: `VersionedInitializable`'s constructor sets
/// `lastInitializedRevision = getRevision()` on the implementation, so direct
/// `initialize(...)` calls on the impl revert with
/// "Contract instance has already been initialized". Do not add
/// `_disableInitializers()` — the function does not exist on this stack.
/// See CLAUDE.md > "No no-op constructors".
contract SpokeUnderlyingManagerInstance is SpokeUnderlyingManager {
    uint256 public constant SPOKE_UM_REVISION = 1;

    constructor(uint256 hubChainId_, address vault_, address crossMessageController_, address accessControl_)
        SpokeUnderlyingManager(hubChainId_, vault_, crossMessageController_, accessControl_)
    {}

    /// @inheritdoc ISpokeUnderlyingManager
    function initialize(address attestationService_) external override initializer {
        __SpokeUnderlyingManager_init(attestationService_);
    }

    /// @notice Returns the revision number
    function getRevision() internal pure override returns (uint256) {
        return SPOKE_UM_REVISION;
    }
}

src/dependencies/VersionedInitializable.sol

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

/**
 * @title VersionedInitializable
 * @author Aave, inspired by the OpenZeppelin Initializable contract
 * @notice Helper contract to implement initializer functions. To use it, replace
 * the constructor with a function that has the `initializer` modifier.
 * @dev WARNING: Unlike constructors, initializer functions must be manually
 * invoked. This applies both to deploying an Initializable contract, as well
 * as extending an Initializable contract via inheritance.
 * WARNING: When used with inheritance, manual care must be taken to not invoke
 * a parent initializer twice, or ensure that all initializers are idempotent,
 * because this is not dealt with automatically as with constructors.
 */
abstract contract VersionedInitializable {
  /**
   * @dev Initializes the implementation contract at the current revision.
   * In practice this breaks further initialization of the implementation.
   */
  constructor() {
    // break the initialize
    lastInitializedRevision = getRevision();
  }

  /**
   * @dev Indicates that the contract has been initialized.
   */
  uint256 private lastInitializedRevision = 0;

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

  /**
   * @dev Modifier to use in the initializer function of a contract.
   */
  modifier initializer() {
    uint256 revision = getRevision();
    require(
      initializing || isConstructor() || revision > lastInitializedRevision,
      'Contract instance has already been initialized'
    );

    bool isTopLevelCall = !initializing;
    if (isTopLevelCall) {
      initializing = true;
      lastInitializedRevision = revision;
    }

    _;

    if (isTopLevelCall) {
      initializing = false;
    }
  }

  /**
   * @notice Returns the revision number of the contract
   * @dev Needs to be defined in the inherited class as a constant.
   * @return The revision number
   */
  function getRevision() internal pure virtual returns (uint256);

  /**
   * @notice Returns true if and only if the function is running in the constructor
   * @return True if the function is running in the constructor
   */
  function isConstructor() private view returns (bool) {
    // extcodesize checks the size of the code stored in an address, and
    // address returns the current address. Since the code is still not
    // deployed when running a constructor, any checks on its code size will
    // yield zero, making it an effective way to detect if a contract is
    // under construction or not.
    uint256 cs;
    //solium-disable-next-line
    assembly {
      cs := extcodesize(address())
    }
    return cs == 0;
  }

  // Reserved storage space to allow for layout changes in the future.
  uint256[50] private ______gap;
}

src/dependencies/openzeppelin/access/IAccessControl.sol

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

pragma solidity >=0.8.4;

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

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

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

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

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

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

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

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

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

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

src/dependencies/openzeppelin/interfaces/IERC1363.sol

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

pragma solidity >=0.6.2;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

src/dependencies/openzeppelin/interfaces/IERC165.sol

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

pragma solidity >=0.4.16;

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

src/dependencies/openzeppelin/interfaces/IERC20.sol

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

pragma solidity >=0.4.16;

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

src/dependencies/openzeppelin/token/ERC20/IERC20.sol

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

pragma solidity >=0.4.16;

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

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

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

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

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

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

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

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

src/dependencies/openzeppelin/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

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

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _safeTransfer(token, to, value, false);
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
     * return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
     * value: the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
     * the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param spender The spender of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

src/dependencies/openzeppelin/utils/Context.sol

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

pragma solidity ^0.8.20;

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

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

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

src/dependencies/openzeppelin/utils/Pausable.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    event Paused(address account);
    event Unpaused(address account);

    error EnforcedPause();
    error ExpectedPause();

    constructor() {
        _paused = false;
    }

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

    modifier whenPaused() {
        _requirePaused();
        _;
    }

    function paused() public view virtual returns (bool) {
        return _paused;
    }

    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

src/dependencies/openzeppelin/utils/ReentrancyGuardTransient.sol

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

pragma solidity ^0.8.24;

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

/**
 * @dev Variant of {ReentrancyGuard} that uses transient storage.
 *
 * NOTE: This variant only works on networks where EIP-1153 is available.
 *
 * _Available since v5.1._
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuardTransient {
    using TransientSlot for *;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().asBoolean().tstore(true);
    }

    function _nonReentrantAfter() private {
        _reentrancyGuardStorageSlot().asBoolean().tstore(false);
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _reentrancyGuardStorageSlot().asBoolean().tload();
    }

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}

src/dependencies/openzeppelin/utils/TransientSlot.sol

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

pragma solidity ^0.8.24;

/**
 * @dev Library for reading and writing value-types to specific transient storage slots.
 *
 * Transient slots are often used to store temporary values that are removed after the current transaction.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 *  * Example reading and writing values using transient storage:
 * ```solidity
 * contract Lock {
 *     using TransientSlot for *;
 *
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
 *
 *     modifier locked() {
 *         require(!_LOCK_SLOT.asBoolean().tload());
 *
 *         _LOCK_SLOT.asBoolean().tstore(true);
 *         _;
 *         _LOCK_SLOT.asBoolean().tstore(false);
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library TransientSlot {
    /**
     * @dev UDVT that represents a slot holding an address.
     */
    type AddressSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a AddressSlot.
     */
    function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
        return AddressSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bool.
     */
    type BooleanSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a BooleanSlot.
     */
    function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
        return BooleanSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bytes32.
     */
    type Bytes32Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Bytes32Slot.
     */
    function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
        return Bytes32Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a uint256.
     */
    type Uint256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Uint256Slot.
     */
    function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
        return Uint256Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a int256.
     */
    type Int256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Int256Slot.
     */
    function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
        return Int256Slot.wrap(slot);
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(AddressSlot slot) internal view returns (address value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(AddressSlot slot, address value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(BooleanSlot slot) internal view returns (bool value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(BooleanSlot slot, bool value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Bytes32Slot slot, bytes32 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Uint256Slot slot) internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Uint256Slot slot, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Int256Slot slot) internal view returns (int256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Int256Slot slot, int256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }
}

src/dependencies/openzeppelin/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/protocol/access/PauseRoles.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;

/**
 * @title PauseRoles
 * @notice Role constants shared by every pausable domain
 */
library PauseRoles {
    /// @notice Gates every unpause function in the protocol and nothing else. Each domain pauses through its own
    ///         pause-only guardian role; one grant of this role per chain lets its holder resume every domain (YEI-1006)
    bytes32 internal constant UNPAUSER_ROLE = keccak256("UNPAUSER_ROLE");
}

src/protocol/attestation/AttestationTypes.sol

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

/// @notice Attestation data structure for transaction pre-authorization
/// @dev Signed by an authorized attester to authorize protected function calls
struct Attestation {
    uint128 uuid;
    uint64 expiration;
    address attester;
    bytes32 r;
    bytes32 s;
    uint8 v;
}

src/protocol/attestation/interfaces/IAttestationService.sol

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

import {Attestation} from "../AttestationTypes.sol";
import {IBaseAttestationService} from "./IBaseAttestationService.sol";

/// @title IAttestationService
/// @notice Interface for the transaction attestation verification service
/// @dev Extends IBaseAttestationService with transaction-specific verify and bypass logic
interface IAttestationService is IBaseAttestationService {
    event AttestationVerified(
        uint128 indexed uuid,
        address indexed from,
        address indexed to,
        address attester,
        uint256 value,
        uint64 expiration
    );

    event BypassChanged(address indexed target, bytes4 indexed selector, bool bypassed);

    error AttestationExpired(uint64 expiration, uint256 currentTime);

    error AttestationRequired();

    /// @notice Reverts when a caller other than the attestation's intended `to` consumer calls `verify`.
    error UnauthorizedConsumer(address caller, address expected);

    /// @notice Reverts when `data` is shorter than the selector + inline `Attestation` struct.
    error MalformedCalldata();

    /// @notice Verifies an attestation for a transaction
    /// @param attestation The attestation to verify
    /// @param from The sender of the transaction (msg.sender in calling contract)
    /// @param to The target contract (address(this) in calling contract)
    /// @param value The ETH value of the transaction (msg.value)
    /// @param data The full calldata (msg.data)
    function verify(Attestation calldata attestation, address from, address to, uint256 value, bytes calldata data)
        external;

    /// @notice Sets bypass for a specific contract + selector combination
    /// @param target Target contract address
    /// @param selector Function selector
    /// @param bypassed Whether to bypass verification
    function setBypass(address target, bytes4 selector, bool bypassed) external;

    /// @notice Generates the EIP-712 hash an attester should sign for the live chain.
    /// @dev Returns the same digest the verifier computes internally; the caller is responsible
    ///      for passing `data` with the inline `Attestation`'s r/s/v bytes already zeroed (the
    ///      verifier re-zeros, so passing fully-populated calldata also works but wastes gas).
    /// @param uuid Unique identifier for replay protection
    /// @param expiration Unix timestamp when attestation expires
    /// @param from Transaction sender address
    /// @param to Target contract address
    /// @param value ETH value of the transaction
    /// @param data Full calldata (>= 196 bytes; see `MalformedCalldata`)
    /// @return The EIP-712 hash to be signed
    function hashForSigning(
        uint128 uuid,
        uint64 expiration,
        address from,
        address to,
        uint256 value,
        bytes calldata data
    ) external view returns (bytes32);

    /// @notice Returns whether bypass is enabled for a contract + selector
    /// @param target Target contract address
    /// @param selector Function selector
    function isBypassEnabled(address target, bytes4 selector) external view returns (bool);
}

src/protocol/attestation/interfaces/IBaseAttestationService.sol

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

/// @title IBaseAttestationService
/// @notice Shared interface for attestation services (attester registry, UUID bitmap, pause)
interface IBaseAttestationService {
    event AttesterRegistered(address indexed attester);

    event AttesterRemoved(address indexed attester);

    event VerificationEnabledChanged(bool enabled);

    error UuidAlreadyUsed(uint128 uuid);

    error InvalidAttester(address attester);

    error InvalidSignature();

    error AttesterAlreadyRegistered(address attester);

    error AttesterNotRegistered(address attester);

    error ZeroAddress();

    function registerAttester(address attester) external;

    function removeAttester(address attester) external;

    function pause() external;

    function unpause() external;

    function setVerificationEnabled(bool enabled) external;

    function isAttesterRegistered(address attester) external view returns (bool);

    function isUuidUsed(uint128 uuid) external view returns (bool);

    function verificationEnabled() external view returns (bool);

    function accessControl() external view returns (address);

    function domainSeparator() external view returns (bytes32);
}

src/protocol/incomeCollector/interfaces/IIncomeCollector.sol

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

import {Attestation} from "../../attestation/AttestationTypes.sol";

/**
 * @title RevenueSource
 * @notice Enum representing different revenue sources in the protocol
 */
enum RevenueSource {
    OTHERS,
    BRIDGE_FEES,
    REBALANCING_FEES,
    ASSET_MANAGEMENT_YIELD,
    LENDING_FEES,
    DEX_FEES
}

/**
 * @title IIncomeCollector
 * @author Clovis Protocol
 * @notice Interface for the IncomeCollector contract
 * @dev Collects fees and income from authorized sources (VaultApps, Bridge contracts, etc.)
 */
interface IIncomeCollector {
    event IncomeCollected(address indexed source, address indexed asset, uint256 amount, RevenueSource revenueSource);

    event SourceAdded(address indexed source);

    event SourceRemoved(address indexed source);

    event SpokeUnderlyingManagerSet(address indexed previousManager, address indexed newManager);

    event RevenueRouterSet(address indexed previousRouter, address indexed newRouter);

    event RevenueDispatched(address indexed asset, uint256 amount, RevenueSource revenueSource, uint256 depositId);

    event UTokenRevenueForwarded(address indexed asset, uint256 amount, RevenueSource revenueSource);

    event EthSwept(address indexed recipient, uint256 amount);

    /**
     * @notice Emitted when booked vault-share revenue is redeemed to its underlying
     * @param vaultShare The ERC-4626 share that was redeemed
     * @param underlying The asset received, re-booked under the same source
     * @param shares Amount of shares redeemed
     * @param received Amount of underlying received, measured by balance diff
     * @param source The revenue source the balance stays booked under
     */
    event VaultSharesRedeemed(
        address indexed vaultShare,
        address indexed underlying,
        uint256 shares,
        uint256 received,
        RevenueSource indexed source
    );

    function initialize(address accessControl_) external;

    function collectIncome(address asset, uint256 amount, RevenueSource revenueSource) external;

    function addSource(address source) external;

    function removeSource(address source) external;

    function setSpokeUnderlyingManager(address spokeUM) external;

    function convertAndSendRevenue(
        Attestation[] calldata attestations,
        address[] calldata assets,
        RevenueSource[] calldata revenueSources
    ) external payable;

    function setRevenueRouter(address revenueRouter) external;

    function sweepEth(address recipient) external;

    /**
     * @notice Redeems booked ERC-4626 vault-share revenue into its underlying asset
     * @dev Moves no value out of the collector — it only changes the denomination of an
     *      already-booked balance, re-booking proceeds under the same revenue source so the
     *      existing uToken branch of convertAndSendRevenue can route them. Hub-only.
     * @param vaultShare The ERC-4626 share to redeem
     * @param revenueSource The source whose booked balance is redeemed
     */
    function redeemVaultShares(address vaultShare, RevenueSource revenueSource) external;

    function isAuthorizedSource(address source) external view returns (bool);

    function getBalance(address asset) external view returns (uint256);

    function getBalanceBySource(address asset, RevenueSource revenueSource) external view returns (uint256);

    function getAccessControl() external view returns (address);

    function getSpokeUnderlyingManager() external view returns (address);

    function getRevenueRouter() external view returns (address);

    function HUB_CHAIN_ID() external view returns (uint256);
}

src/protocol/mba/handlers/MessageHandlerUpgradeable.sol

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

import {IMessageHandler} from "../interfaces/IMessageHandler.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {MessageOrigin} from "../libraries/MessageLib.sol";
import {AddressConversion} from "../libraries/AddressConversion.sol";
import {ICrossMessageController} from "../interfaces/ICrossMessageController.sol";
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {InvalidPeer, MessageTooOld, UnauthorizedSender, ZeroAddress} from "../interfaces/MBAErrors.sol";
import {VersionedInitializable} from "../../../dependencies/VersionedInitializable.sol";

/**
 * @title MessageHandlerUpgradeable
 * @author Clovis Protocol
 * @notice Abstract base contract for upgradeable message handlers
 * @dev Provides EIP-165 support, controller authorization, peer validation, age validation, and base handleMessage implementation
 * @dev Handlers should extend this contract and implement _handleMessage() for business logic
 * @dev Uses VersionedInitializable pattern for proxy compatibility
 */
abstract contract MessageHandlerUpgradeable is IMessageHandler, VersionedInitializable {
    using AddressConversion for address;

    /// @notice Role required to manage peers
    bytes32 public constant MESSAGE_HANDLER_ADMIN_ROLE = keccak256("MESSAGE_HANDLER_ADMIN_ROLE");

    /// @notice Default maximum age for messages (12 hours)
    uint256 public constant DEFAULT_MAX_AGE = 12 hours;

    /// @notice CrossMessageController that is authorized to call handleMessage
    ICrossMessageController public immutable CROSS_MESSAGE_CONTROLLER;

    /// @notice Access control contract for role-based permissions
    IAccessControl public immutable ACCESS_CONTROL;

    /// @notice Mapping of valid peers: chainId => peerAddress (bytes32) => isValid
    /// @dev Used to validate that incoming messages are from trusted sources
    /// @dev Uses bytes32 to support both EVM addresses (left-padded) and non-EVM addresses (e.g., Solana pubkeys)
    mapping(uint256 => mapping(bytes32 => bool)) internal _peers;

    /// @notice Optional override for the maximum message age (in seconds)
    /// @dev Zero means "use DEFAULT_MAX_AGE". Non-zero value takes precedence over the default.
    uint256 internal _maxAgeOverride;

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

    /// @notice Emitted when a peer is added
    event PeerSet(uint256 indexed chainId, bytes32 indexed peer);

    /// @notice Emitted when a peer is removed
    event PeerRemoved(uint256 indexed chainId, bytes32 indexed peer);

    /// @notice Emitted when the max age override is updated
    /// @param oldValue Previous override (0 means default was in effect)
    /// @param newValue New override (0 means fall back to DEFAULT_MAX_AGE)
    event MaxAgeSet(uint256 oldValue, uint256 newValue);

    /**
     * @notice Restricts access to only the messageController
     */
    modifier onlyController() {
        if (msg.sender != address(CROSS_MESSAGE_CONTROLLER)) revert UnauthorizedSender();
        _;
    }

    /**
     * @notice Restricts access to accounts with a specific role
     * @param role The role required to call the function
     */
    modifier onlyRole(bytes32 role) {
        _mustBeRole(role);
        _;
    }

    constructor(address crossMessageController_, address accessControl_) {
        if (crossMessageController_ == address(0)) revert ZeroAddress();
        if (accessControl_ == address(0)) revert ZeroAddress();
        CROSS_MESSAGE_CONTROLLER = ICrossMessageController(crossMessageController_);
        ACCESS_CONTROL = IAccessControl(accessControl_);
    }

    /**
     * @notice Handle incoming cross-chain message (implements IMessageHandler)
     * @dev Called by CrossMessageController after consensus is reached
     * @dev Enforces controller-only access, validates peer, validates message age, and delegates to internal _handleMessage
     * @param messageId Unique message identifier
     * @param payload Encoded message payload
     * @param origin Source chain metadata (chainId, sender, timestamp)
     * @return success Whether handling succeeded
     */
    function handleMessage(bytes32 messageId, bytes calldata payload, MessageOrigin calldata origin)
        external
        virtual
        override
        onlyController
        returns (bool success)
    {
        // Validate peer unconditionally. The previous same-chain bypass relied on the
        // controller's `MBA_OPERATOR_ROLE` to gate same-chain senders, but that role is
        // granted to multiple counterparties (every UM proxy, every BridgeVaultApp
        // proxy, and a configured operator EOA) — broader than this handler's
        // intended counterparty. With Hub-as-Spoke deployments the same-chain branch
        // is the UM↔UM happy path and is peer-checked symmetrically with cross-chain
        // messages.
        if (!_peers[origin.sourceChainId][origin.sourceSender]) {
            revert InvalidPeer();
        }

        // Validate message age
        uint256 maxAge = getMaxAge(origin);
        uint256 age = block.timestamp - origin.sourceTimestamp;
        if (age > maxAge) {
            revert MessageTooOld(origin.sourceTimestamp, maxAge);
        }

        return _handleMessage(messageId, payload, origin);
    }

    /**
     * @notice Set the max age override
     * @dev Only callable by accounts with MESSAGE_HANDLER_ADMIN_ROLE
     * @dev Pass 0 to clear the override and fall back to DEFAULT_MAX_AGE
     * @param newMaxAge New maximum age in seconds, or 0 to use default
     */
    function setMaxAge(uint256 newMaxAge) external virtual onlyRole(MESSAGE_HANDLER_ADMIN_ROLE) {
        uint256 oldValue = _maxAgeOverride;
        _maxAgeOverride = newMaxAge;
        emit MaxAgeSet(oldValue, newMaxAge);
    }

    /**
     * @notice Set a peer for cross-chain communication using bytes32
     * @dev Only callable by accounts with MESSAGE_HANDLER_ADMIN_ROLE
     * @param chainId Chain ID of the peer
     * @param peer Peer address as bytes32
     */
    function setPeer(uint256 chainId, bytes32 peer) external virtual onlyRole(MESSAGE_HANDLER_ADMIN_ROLE) {
        _setPeer(chainId, peer);
    }

    /**
     * @notice Set a peer for cross-chain communication using EVM address
     * @dev Only callable by accounts with MESSAGE_HANDLER_ADMIN_ROLE
     * @param chainId Chain ID of the peer
     * @param peer EVM address of the peer
     */
    function setPeerAddress(uint256 chainId, address peer) external virtual onlyRole(MESSAGE_HANDLER_ADMIN_ROLE) {
        _setPeer(chainId, peer.addressToBytes32());
    }

    /**
     * @notice Remove a peer using bytes32
     * @dev Only callable by accounts with MESSAGE_HANDLER_ADMIN_ROLE
     * @param chainId Chain ID of the peer
     * @param peer Peer address as bytes32 to remove
     */
    function removePeer(uint256 chainId, bytes32 peer) external virtual onlyRole(MESSAGE_HANDLER_ADMIN_ROLE) {
        _removePeer(chainId, peer);
    }

    /**
     * @notice Remove a peer using EVM address
     * @dev Only callable by accounts with MESSAGE_HANDLER_ADMIN_ROLE
     * @param chainId Chain ID of the peer
     * @param peer EVM address of the peer to remove
     */
    function removePeerAddress(uint256 chainId, address peer) external virtual onlyRole(MESSAGE_HANDLER_ADMIN_ROLE) {
        _removePeer(chainId, peer.addressToBytes32());
    }

    /**
     * @notice Get maximum allowed age for a message
     * @dev Returns the admin-configured override when set, otherwise DEFAULT_MAX_AGE
     * @dev Override this function to customize age limits per message type or origin
     * @param origin Source chain metadata
     * @return Maximum age in seconds
     */
    function getMaxAge(MessageOrigin calldata origin) public view virtual returns (uint256) {
        uint256 override_ = _maxAgeOverride;
        return override_ == 0 ? DEFAULT_MAX_AGE : override_;
    }

    /**
     * @notice EIP-165 interface detection
     * @dev Returns true for IMessageHandler and IERC165 interfaces
     * @param interfaceId Interface identifier to check
     * @return True if interface is supported
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IMessageHandler).interfaceId || interfaceId == type(IERC165).interfaceId;
    }

    /**
     * @notice Check if a bytes32 address is a valid peer for a given chain
     * @param chainId Chain ID to check
     * @param peer Peer address as bytes32
     * @return True if the address is a valid peer for the chain
     */
    function isPeer(uint256 chainId, bytes32 peer) public view virtual returns (bool) {
        return _peers[chainId][peer];
    }

    /**
     * @notice Check if an EVM address is a valid peer for a given chain
     * @param chainId Chain ID to check
     * @param peer EVM address to check
     * @return True if the address is a valid peer for the chain
     */
    function isPeerAddress(uint256 chainId, address peer) public view virtual returns (bool) {
        return _peers[chainId][peer.addressToBytes32()];
    }

    /**
     * @notice Internal message handling logic to be implemented by derived contracts
     * @dev Override this function to implement your handler's business logic
     * @param messageId Unique message identifier
     * @param payload Encoded message payload
     * @param origin Source chain metadata
     * @return success Whether handling succeeded
     */
    function _handleMessage(bytes32 messageId, bytes calldata payload, MessageOrigin calldata origin)
        internal
        virtual
        returns (bool success);

    /**
     * @notice Internal function to set a peer
     * @param chainId Chain ID of the peer
     * @param peer Peer address as bytes32
     */
    function _setPeer(uint256 chainId, bytes32 peer) internal virtual {
        if (peer == bytes32(0)) revert ZeroAddress();
        if (chainId == 0) revert InvalidPeer();
        // Same-chain registration is allowed: with Hub-as-Spoke deployments the local
        // counterparty (e.g. SpokeUM ↔ HubUM on the same chain) must be a registered
        // peer just like cross-chain counterparties. The `handleMessage` peer check
        // is unconditional.
        _peers[chainId][peer] = true;
        emit PeerSet(chainId, peer);
    }

    /**
     * @notice Internal function to set a peer using EVM address
     * @param chainId Chain ID of the peer
     * @param peer EVM address of the peer
     */
    function _setPeerAddress(uint256 chainId, address peer) internal virtual {
        _setPeer(chainId, peer.addressToBytes32());
    }

    /**
     * @notice Internal function to remove a peer
     * @param chainId Chain ID of the peer
     * @param peer Peer address as bytes32 to remove
     */
    function _removePeer(uint256 chainId, bytes32 peer) internal virtual {
        _peers[chainId][peer] = false;
        emit PeerRemoved(chainId, peer);
    }

    /**
     * @notice Internal function to remove a peer using EVM address
     * @param chainId Chain ID of the peer
     * @param peer EVM address of the peer to remove
     */
    function _removePeerAddress(uint256 chainId, address peer) internal virtual {
        _removePeer(chainId, peer.addressToBytes32());
    }

    function _mustBeRole(bytes32 role) internal view {
        if (!ACCESS_CONTROL.hasRole(role, msg.sender)) {
            revert IAccessControl.AccessControlUnauthorizedAccount(msg.sender, role);
        }
    }
}

src/protocol/mba/interfaces/ICrossMessageController.sol

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

import {MessageState, MessageStatus, MessageType, OutboundMessage} from "../libraries/MessageLib.sol";
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";

enum MessageSkipReason {
    ALREADY_EXECUTED,
    FORCE_RESOLVED,
    DUPLICATE_CONFIRMATION
}

struct SourcePreset {
    bytes32 presetId;
    bytes32 name;
    uint256 destChainId;
    address[] adapters;
    uint256 quorum;
    uint256 maxUnderlyingValueUSD;
    uint256 suggestedFeeBps;
    bool enabled;
}

struct DestPreset {
    bytes32 presetId;
    bytes32 name;
    uint256 srcChainId;
    address[] adapters;
    uint256 quorum;
    bool enabled;
}

/**
 * @title ICrossMessageController
 * @author Clovis Protocol
 * @notice Interface for the main CrossMessageController contract
 * @dev Central contract for cross-chain messaging with multi-bridge consensus
 */
interface ICrossMessageController {
    /**
     * @notice Emitted when an inbound message is silently skipped (no-op)
     * @param messageId Message identifier
     * @param bridge Bridge adapter that delivered the message
     * @param reason Why the message was skipped
     */
    event MessageSkipped(bytes32 indexed messageId, address indexed bridge, MessageSkipReason reason);

    /**
     * @notice Emitted when a new message is initiated
     * @param messageId Unique message identifier
     * @param sender Message sender
     * @param destChainId Destination chain ID
     * @param msgType Type of message
     * @param presetId Source preset used (bytes32(0) for same-chain or default)
     * @param payload Message payload
     */
    event MessageInitiated(
        bytes32 indexed messageId,
        address indexed sender,
        uint256 indexed destChainId,
        MessageType msgType,
        bytes32 presetId,
        bytes payload
    );

    /**
     * @notice Emitted when a message is sent via a bridge
     * @param messageId Unique message identifier
     * @param bridge Bridge adapter address
     * @param bridgeTxId Bridge-specific transaction ID
     */
    event MessageSentViaBridge(bytes32 indexed messageId, address indexed bridge, bytes32 bridgeTxId);

    /**
     * @notice Emitted when a bridge fails to send a message
     * @param messageId Unique message identifier
     * @param bridge Bridge adapter address that failed
     * @param reason Failure reason (if available)
     */
    event BridgeSendFailed(bytes32 indexed messageId, address indexed bridge, string reason);

    /**
     * @notice Emitted when a message confirmation is received
     * @param messageId Unique message identifier
     * @param bridge Bridge adapter that confirmed
     * @param confirmationCount Total confirmations received
     */
    event MessageConfirmed(bytes32 indexed messageId, address indexed bridge, uint256 confirmationCount);

    /**
     * @notice Emitted when a message is executed
     * @param messageId Unique message identifier
     * @param success Whether execution succeeded
     */
    event MessageExecuted(bytes32 indexed messageId, bool success);

    /**
     * @notice Emitted when message execution fails
     * @param messageId Unique message identifier
     * @param reason Failure reason
     */
    event ExecutionFailed(bytes32 indexed messageId, string reason);

    /**
     * @notice Emitted when a message is retried
     * @param messageId Unique message identifier
     * @param retryCount Current retry count
     */
    event MessageRetried(bytes32 indexed messageId, uint8 retryCount);

    /**
     * @notice Emitted when a failed handler execution is retried
     * @param messageId Message identifier
     * @param retrier Address that triggered the retry
     * @param success Whether the retry succeeded
     */
    event HandlerRetried(bytes32 indexed messageId, address indexed retrier, bool success);

    /**
     * @notice Emitted when an admin resets a retry counter
     * @dev Shared by both sender (outbound) and receiver (inbound) resets; the calling method
     *      (`resetSenderRetryCount` vs `resetReceiverRetryCount`) disambiguates which side was reset.
     * @param messageId Message identifier
     * @param admin Admin who reset the counter
     */
    event RetryCountReset(bytes32 indexed messageId, address indexed admin);

    /**
     * @notice Emitted when a bridge adapter is added
     * @param chainId Target chain ID
     * @param bridge Bridge adapter address
     * @param bridgeName Immutable bytes32 name of the adapter instance
     * @param bridgeProvider Constant bytes32 identifying the underlying bridge infrastructure
     */
    event BridgeAdapterAdded(
        uint256 indexed chainId, address indexed bridge, bytes32 bridgeName, bytes32 bridgeProvider
    );

    /**
     * @notice Emitted when a source preset is created
     * @param presetId Unique preset identifier
     * @param name Human-readable name as bytes32
     * @param destChainId Destination chain ID this preset targets
     * @param adapters Ordered list of adapter addresses
     * @param quorum Minimum confirmations required for delivery
     * @param maxUnderlyingValueUSD Max USD value allowed per message (0 = unlimited)
     * @param suggestedFeeBps Fee in basis points applied by callers
     */
    event SourcePresetCreated(
        bytes32 indexed presetId,
        bytes32 indexed name,
        uint256 destChainId,
        address[] adapters,
        uint256 quorum,
        uint256 maxUnderlyingValueUSD,
        uint256 suggestedFeeBps
    );

    /**
     * @notice Emitted when a destination preset is created
     * @param presetId Unique preset identifier
     * @param name Human-readable name as bytes32
     * @param srcChainId Source chain ID this preset accepts from
     * @param adapters Allowlisted receiving adapters that may confirm this preset
     * @param quorum Minimum confirmations required to execute
     */
    event DestPresetCreated(
        bytes32 indexed presetId, bytes32 indexed name, uint256 srcChainId, address[] adapters, uint256 quorum
    );

    /**
     * @notice Emitted when a preset is disabled
     * @param presetId Preset identifier
     */
    event PresetDisabled(bytes32 indexed presetId);

    /**
     * @notice Emitted when a preset is enabled
     * @param presetId Preset identifier
     */
    event PresetEnabled(bytes32 indexed presetId);

    /// @notice Emitted when a preset is permanently deleted
    event PresetDeleted(bytes32 indexed presetId);

    /**
     * @notice Emitted when a default preset is set for a destination chain
     * @param destChainId Destination chain ID
     * @param presetId Default preset identifier
     */
    event DefaultPresetSet(uint256 indexed destChainId, bytes32 indexed presetId);

    /**
     * @notice Emitted when a message is force-resolved by admin
     * @param messageId Message identifier
     * @param executed Whether the message was executed (true) or permanently failed (false)
     * @param status Resulting message status after force resolution
     */
    event MessageForceResolved(bytes32 indexed messageId, bool executed, MessageStatus status);

    /**
     * @notice Emitted when a bridge adapter is removed
     * @param chainId Target chain ID
     * @param bridge Bridge adapter address
     */
    event BridgeAdapterRemoved(uint256 indexed chainId, address indexed bridge);

    /**
     * @notice Emitted when system is paused
     * @param guardian Guardian who paused
     */
    event SystemPaused(address indexed guardian);

    /**
     * @notice Emitted when system is unpaused
     * @param admin The UNPAUSER_ROLE holder who unpaused
     */
    event SystemUnpaused(address indexed admin);

    /**
     * @notice Emitted when the time before force resolve is updated
     * @param oldValue Previous value in seconds
     * @param newValue New value in seconds
     */
    event TimeBeforeForceResolveUpdated(uint256 oldValue, uint256 newValue);

    /**
     * @notice Emitted when a message handler is set
     * @param msgType Message type
     * @param handler Handler contract address
     */
    event MessageHandlerSet(MessageType indexed msgType, address indexed handler);

    /**
     * @notice Emitted when stuck native tokens are rescued
     * @param admin Admin who rescued the funds
     * @param amount Amount rescued
     */
    event NativeTokensRescued(address indexed admin, uint256 amount);

    /**
     * @notice Emitted when stuck ERC20 tokens are rescued
     * @param token Token address
     * @param admin Admin who rescued the funds
     * @param amount Amount rescued
     */
    event TokensRescued(address indexed token, address indexed admin, uint256 amount);

    /**
     * @notice Initialize the CrossMessageController contract
     * @param accessControl The address of the AccessControl contract
     */
    function initialize(address accessControl) external;

    /**
     * @notice Send a cross-chain message using a specific preset
     * @param destinationChainId Destination chain ID
     * @param message Encoded message
     * @param msgType Type of message
     * @param adapterValues Array of values to send to each adapter (must match preset adapter count)
     * @param presetId Source preset to use (bytes32(0) = use default)
     * @param underlyingValueUSD USD value for max-value check (0 = skip check)
     * @return messageId Unique message identifier
     */
    function sendMessage(
        uint256 destinationChainId,
        bytes calldata message,
        MessageType msgType,
        uint256[] calldata adapterValues,
        bytes32 presetId,
        uint256 underlyingValueUSD
    ) external payable returns (bytes32 messageId);

    /**
     * @notice Send a cross-chain message using the default preset
     * @param destinationChainId Destination chain ID
     * @param message Encoded message
     * @param msgType Type of message
     * @param adapterValues Array of values to send to each adapter (must match number of bridges)
     * @return messageId Unique message identifier
     */
    function sendMessage(
        uint256 destinationChainId,
        bytes calldata message,
        MessageType msgType,
        uint256[] calldata adapterValues
    ) external payable returns (bytes32 messageId);

    /**
     * @notice Receive a message from a bridge adapter
     * @dev Caller (msg.sender) must be an authorized bridge adapter
     * @param encodedMessage Encoded cross-chain message
     */
    function receiveMessage(bytes calldata encodedMessage) external;

    /**
     * @notice Retry a failed or stuck message with fresh adapter fees
     * @param messageId Message to retry
     * @param adapterValues Fresh fee values for each adapter in the current preset
     */
    function retryMessage(bytes32 messageId, uint256[] calldata adapterValues) external payable;

    /**
     * @notice Reset the outbound (sender-side) retry counter for a message that has exhausted its retries
     * @dev Admin-only. Does NOT reset lastRetryAt, so the first retry after reset still observes backoff.
     * @param messageId Message identifier to reset
     */
    function resetSenderRetryCount(bytes32 messageId) external;

    /**
     * @notice Reset the inbound (receiver-side) execution-retry counter for a stuck message
     * @dev Admin-only recovery path. After `retryExecution` hits the execution-retry cap and reverts
     *      `MaxRetriesExceeded`, the admin fixes the transient cause and calls this to re-open retries.
     * @param messageId Message identifier to reset
     */
    function resetReceiverRetryCount(bytes32 messageId) external;

    /**
     * @notice Retry execution of a failed inbound message handler
     * @dev Permissionless. Validates message is in failed state and dest preset is enabled.
     * @param messageId Message to retry execution for
     */
    function retryExecution(bytes32 messageId) external;

    /**
     * @notice Create a source preset defining how messages are sent to a destination chain
     * @param presetId Unique preset identifier (computed off-chain)
     * @param name Human-readable name as bytes32
     * @param destChainId Destination chain ID
     * @param adapters Ordered list of adapter addresses
     * @param quorum Minimum confirmations for delivery
     * @param maxUnderlyingValueUSD Max USD value per message (0 = unlimited)
     * @param suggestedFeeBps Fee in basis points applied by callers
     */
    function createSourcePreset(
        bytes32 presetId,
        bytes32 name,
        uint256 destChainId,
        address[] calldata adapters,
        uint256 quorum,
        uint256 maxUnderlyingValueUSD,
        uint256 suggestedFeeBps
    ) external;

    /**
     * @notice Create a destination preset defining how messages are received from a source chain
     * @param presetId Unique preset identifier (must match source chain's presetId)
     * @param name Human-readable name as bytes32
     * @param srcChainId Source chain ID
     * @param adapters Allowlisted local receiving adapters that may confirm toward quorum
     * @param quorum Minimum confirmations to execute
     */
    function createDestPreset(
        bytes32 presetId,
        bytes32 name,
        uint256 srcChainId,
        address[] calldata adapters,
        uint256 quorum
    ) external;

    /**
     * @notice Enable a previously disabled preset
     * @param presetId Preset identifier
     */
    function enablePreset(bytes32 presetId) external;

    /**
     * @notice Disable a preset (prevents new sends/receives)
     * @param presetId Preset identifier
     */
    function disablePreset(bytes32 presetId) external;

    /**
     * @notice Permanently delete a preset, freeing its ID for re-creation
     * @dev Cannot delete a preset that is currently set as default
     * @param presetId Preset identifier
     */
    function deletePreset(bytes32 presetId) external;

    /**
     * @notice Set the default source preset for a destination chain
     * @param destChainId Destination chain ID
     * @param presetId Preset identifier (must be enabled and target destChainId)
     */
    function setDefaultPreset(uint256 destChainId, bytes32 presetId) external;

    /**
     * @notice Force-resolve a stuck message by executing or permanently failing it
     * @param messageId Message identifier
     * @param execute True to execute bypassing quorum, false to permanently fail
     */
    function forceResolveMessage(bytes32 messageId, bool execute) external;

    /**
     * @notice Add a bridge adapter for a chain
     * @param chainId Target chain ID
     * @param bridge Bridge adapter address
     */
    function addBridgeAdapter(uint256 chainId, address bridge) external;

    /**
     * @notice Remove a bridge adapter for a chain
     * @param chainId Target chain ID
     * @param bridge Bridge adapter address
     */
    function removeBridgeAdapter(uint256 chainId, address bridge) external;

    /**
     * @notice Emergency pause all message processing
     * @dev MBA_GUARDIAN_ROLE (pause-only). A repeated call returns without effect
     */
    function emergencyPause() external;

    /**
     * @notice Unpause the system
     * @dev UNPAUSER_ROLE
     */
    function emergencyUnpause() external;

    /**
     * @notice Emergency remove a bridge adapter from every chain, disabling the presets that use it
     * @dev MBA_QUARANTINE_ROLE or MBA_ADMIN_ROLE
     * @param bridge Bridge adapter to remove
     */
    function emergencyRemoveBridge(address bridge) external;

    /**
     * @notice Set message handler for a message type
     * @param msgType Message type
     * @param handler Handler contract address
     */
    function setMessageHandler(MessageType msgType, address handler) external;

    /**
     * @notice Set the minimum time (in seconds) that must elapse after a message is first received
     *         before the admin can call forceResolveMessage
     * @param timeBeforeForceResolve New value in seconds
     */
    function setTimeBeforeForceResolve(uint256 timeBeforeForceResolve) external;

    /**
     * @notice Rescue stuck native tokens from the contract
     * @dev Sends to msg.sender for security (no arbitrary recipient)
     * @param amount Amount to rescue (use type(uint256).max for full balance)
     */
    function rescueNativeTokens(uint256 amount) external;

    /**
     * @notice Rescue stuck ERC20 tokens from the contract
     * @dev Sends to msg.sender for security (no arbitrary recipient)
     * @param token Token address
     * @param amount Amount to rescue (use type(uint256).max for full balance)
     */
    function rescueTokens(address token, uint256 amount) external;

    /**
     * @notice Get access control contract
     * @return Access control contract address
     */
    function accessControl() external view returns (IAccessControl);

    /**
     * @notice Get message status
     * @param messageId Message ID to query
     * @return state Complete message state
     */
    function getMessageStatus(bytes32 messageId) external view returns (MessageState memory state);

    /**
     * @notice Get the default source preset for a destination chain
     * @param destChainId Destination chain ID
     * @return presetId Default preset identifier
     */
    function getDefaultPreset(uint256 destChainId) external view returns (bytes32 presetId);

    /**
     * @notice Get a source preset by ID
     * @param presetId Preset identifier
     * @return Source preset struct
     */
    function getSourcePreset(bytes32 presetId) external view returns (SourcePreset memory);

    /**
     * @notice Get a destination preset by ID
     * @param presetId Preset identifier
     * @return Destination preset struct
     */
    function getDestPreset(bytes32 presetId) external view returns (DestPreset memory);

    /**
     * @notice Get the suggested fee in basis points for a preset
     * @param presetId Preset identifier
     * @return suggestedFeeBps Fee in basis points
     */
    function getPresetFee(bytes32 presetId) external view returns (uint256 suggestedFeeBps);

    /**
     * @notice Get all bridges for a chain
     * @param chainId Chain ID to query
     * @return bridges Array of bridge adapter addresses
     */
    function getBridges(uint256 chainId) external view returns (address[] memory bridges);

    /**
     * @notice Check if system is paused
     * @return True if paused
     */
    function isPaused() external view returns (bool);

    /**
     * @notice Get sender's nonce
     * @param sender Address to query
     * @return Current nonce
     */
    function getNonce(address sender) external view returns (uint256);

    /**
     * @notice Estimate total fees for sending a message using a specific preset
     * @param destChainId Destination chain ID
     * @param payload Application payload
     * @param msgType Type of message
     * @param presetId Source preset to estimate for (bytes32(0) = use default)
     * @return totalFee Total native token required
     * @return adapterValues Array of fees per adapter (in same order as preset adapters)
     */
    function estimateFees(uint256 destChainId, bytes calldata payload, MessageType msgType, bytes32 presetId)
        external
        view
        returns (uint256 totalFee, uint256[] memory adapterValues);

    /**
     * @notice Estimate total fees for sending a message using the default preset
     * @param destChainId Destination chain ID
     * @param payload Application payload
     * @param msgType Type of message
     * @return totalFee Total native token required
     * @return adapterValues Array of fees per adapter (in same order as bridges)
     */
    function estimateFees(uint256 destChainId, bytes calldata payload, MessageType msgType)
        external
        view
        returns (uint256 totalFee, uint256[] memory adapterValues);

    /**
     * @notice Get message handler for a message type
     * @param msgType Message type
     * @return Handler contract address
     */
    function getMessageHandler(MessageType msgType) external view returns (address);

    /**
     * @notice Get all source preset IDs for a destination chain
     * @param destChainId Destination chain ID
     * @return Array of source preset identifiers
     */
    function getSourcePresetsForChain(uint256 destChainId) external view returns (bytes32[] memory);

    /**
     * @notice Get the minimum time before force resolve is allowed
     * @return Minimum time in seconds
     */
    function getTimeBeforeForceResolve() external view returns (uint256);

    /**
     * @notice Get outbound message details by message ID
     * @param messageId Message identifier
     * @return Outbound message struct (empty if not found)
     */
    function getOutboundMessage(bytes32 messageId) external view returns (OutboundMessage memory);

    /**
     * @notice Check whether an outbound message can be retried
     * @param messageId Message identifier
     * @return canRetry_ True if the message exists, has not exceeded max retries, and the backoff has elapsed
     * @return retryCount Current retry count
     * @return nextRetryAt Timestamp after which the next retry is allowed (0 if message not found)
     */
    function canRetryOutbound(bytes32 messageId)
        external
        view
        returns (bool canRetry_, uint8 retryCount, uint256 nextRetryAt);

    /**
     * @notice Check whether a failed inbound message execution can be retried
     * @param messageId Message identifier
     * @return True if the message is in a failed execution state and its dest preset is enabled
     */
    function canRetryExecution(bytes32 messageId) external view returns (bool);
}

src/protocol/mba/interfaces/IMessageHandler.sol

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

import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {MessageOrigin} from "../libraries/MessageLib.sol";

/**
 * @title IMessageHandler
 * @author Clovis Protocol
 * @notice Interface for contracts that handle cross-chain messages
 * @dev Handlers must implement this interface and EIP-165 to be registered with CrossMessageController
 */
interface IMessageHandler is IERC165 {
    /**
     * @notice Handle a cross-chain message
     * @param messageId Unique message identifier
     * @param payload Message payload to process
     * @param origin Source chain metadata (chainId, sender, timestamp)
     * @return success Whether handling succeeded
     */
    function handleMessage(bytes32 messageId, bytes calldata payload, MessageOrigin calldata origin)
        external
        returns (bool success);
}

src/protocol/mba/interfaces/MBAErrors.sol

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

// MBAErrors
// Clovis Protocol
// Custom errors for the Message Bridge Aggregator system
// Using custom errors for gas efficiency. Errors are defined at file level following modern Solidity patterns.

// Access Control Errors
error UnauthorizedSender();
error UnauthorizedBridge();
error InvalidRole();

// Message Errors
error MessageAlreadyExecuted();
error MessageNotFound();
error InvalidMessageId();

error QuorumNotReached();
error MessageExecutionFailed();
error InvalidPayload();
error InvalidDestinationChain();

// Bridge Configuration Errors
error InvalidBridgeAdapter();
error BridgeAlreadyRegistered();
error BridgeNotRegistered();
error InsufficientBridges();
error InvalidQuorumConfig();
error ChainNotSupported();

// Preset Errors
error PresetNotFound(bytes32 presetId);
error PresetIsDisabled(bytes32 presetId);
error PresetAdapterNotSupported(bytes32 presetId, address adapter);
error InvalidQuorum(uint256 quorum, uint256 adapterCount);
error PresetAlreadyExists(bytes32 presetId);
error DefaultPresetAffected(bytes32 presetId, uint256 destChainId);
error MaxUnderlyingValueExceeded(uint256 value, uint256 maxValue);
error ZeroPresetId();
error NoDefaultPreset(uint256 destChainId);
error DuplicateAdapter(address adapter);
error MessageIdMismatch(bytes32 claimedId, bytes32 computedId);
error MessageAlreadyForceResolved(bytes32 messageId);

// Retry Errors
error MaxRetriesExceeded();
error RetryTooSoon();
error CannotRetryExecutedMessage();
error InsufficientBridgeSends(uint256 successCount, uint256 requiredQuorum);
error MessageNotFailed();
error ForceResolveTooSoon(uint256 receivedAt, uint256 earliestResolveAt);

// System State Errors
error MBAPaused();
error MBANotPaused();
error InvalidChainId();
error ZeroAddress();

// Fee Errors
error InsufficientFee();
error FeeTransferFailed();
error InsufficientValue();
error InsufficientFunds();
error TransferFailed();
error SameChainMessageWithValue();

// Handler Errors
error InvalidHandler();
error MessageTooOld(uint256 sourceTimestamp, uint256 maxAge);

// Source Chain Errors
error InvalidSourceChain();

// Peer Errors
error InvalidPeer();

// Adapter Errors
error MessageForwardReverted(bytes32 messageId, uint256 sourceChainId, bytes returnData);

src/protocol/mba/libraries/AddressConversion.sol

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

/**
 * @title AddressConversion
 * @author Clovis Protocol
 * @notice Library for converting between EVM addresses and bytes32 for cross-chain compatibility
 * @dev Follows LayerZero pattern to support both EVM and non-EVM chains (e.g., Solana)
 */
library AddressConversion {
    /**
     * @notice Convert EVM address to bytes32
     * @dev Left-pads the address with zeros to create a 32-byte representation
     * @param addr EVM address to convert
     * @return bytes32 representation of the address
     */
    function addressToBytes32(address addr) internal pure returns (bytes32) {
        return bytes32(uint256(uint160(addr)));
    }

    /**
     * @notice Convert bytes32 to EVM address
     * @dev Takes the last 20 bytes of the bytes32 value
     * @param b bytes32 value to convert
     * @return address EVM address extracted from bytes32
     */
    function bytes32ToAddress(bytes32 b) internal pure returns (address) {
        return address(uint160(uint256(b)));
    }

    /**
     * @notice Check if bytes32 represents a valid EVM address
     * @dev Valid EVM addresses have first 12 bytes as zero (only last 20 bytes used)
     * @param b bytes32 value to validate
     * @return bool True if the bytes32 can represent a valid EVM address
     */
    function isValidEvmAddress(bytes32 b) internal pure returns (bool) {
        return uint256(b) <= type(uint160).max;
    }
}

src/protocol/mba/libraries/MessageLib.sol

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

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

// MessageLib
// Clovis Protocol
// Library for encoding, decoding, and generating message IDs
// Handles all message-related operations for the MBA system

// Chain ID constants for non-EVM chains
uint256 constant SOLANA_MAINNET_CHAIN_ID = 1000000001;
uint256 constant SOLANA_DEVNET_CHAIN_ID = 1000000002;

// Message types supported by the system
enum MessageType {
    DEPOSIT, // Spoke -> Hub: User deposits
    WITHDRAWAL, // Hub -> Spoke: Withdrawal requests
    BRIDGE // Spoke -> Spoke: Bridge assets
}

// Message execution status
enum MessageStatus {
    PENDING, // Waiting for confirmations
    CONFIRMED, // Quorum reached
    EXECUTED, // Successfully executed
    FAILED // Execution failed
}

// Origin metadata passed to message handlers
struct MessageOrigin {
    uint256 sourceChainId;
    bytes32 sourceSender;
    uint256 sourceTimestamp;
}

// Complete cross-chain message structure
struct CrossChainMessage {
    bytes32 messageId; // Unique message identifier
    bytes32 presetId; // Preset used for this message (bytes32(0) = default was resolved)
    MessageType msgType; // Type of message
    uint256 sourceChainId; // Source chain ID
    uint256 destChainId; // Destination chain ID
    bytes32 sender; // Original sender on source chain (bytes32 for EVM and non-EVM support)
    uint256 nonce; // Sender's message nonce
    bytes payload; // Application-specific data
    uint256 timestamp; // Block timestamp at send
}

// Outbound message tracking on source chain
struct OutboundMessage {
    bytes32 messageId;
    uint256 destChainId;
    MessageType msgType;
    address sender;
    uint256 nonce;
    bytes payload;
    uint256 timestamp;
    uint8 retryCount;
    uint256 lastRetryAt;
    bool sent;
    uint256[] adapterValues;
    bytes32 presetId;
}

// Message state tracking on destination chain
struct MessageState {
    bytes32 messageId;
    MessageType msgType;
    uint256 sourceChainId;
    uint256 destChainId;
    bytes32 sourceSender;
    uint256 sourceTimestamp;
    bytes payload;
    uint256 confirmations;
    uint256 receivedAt;
    uint256 executedAt;
    bool executed;
    bool failed;
    uint8 retryCount;
    uint256 lastRetryAt;
    bytes32 presetId;
    MessageStatus status;
}

// Message information for queries
struct MessageInfo {
    bytes32 messageId;
    MessageType msgType;
    uint256 sourceChainId;
    uint256 destChainId;
    bytes32 sender;
    uint256 timestamp;
    MessageStatus status;
    uint256 confirmations;
}

library MessageLib {
    using AddressConversion for address;

    /**
     * @notice Generate unique message ID from EVM address sender
     * @dev Converts address to bytes32 internally for consistent hashing
     * @param sourceChainId Source chain identifier
     * @param sender Message sender address (EVM)
     * @param nonce Sender's nonce
     * @param payload Message payload
     * @param timestamp Block timestamp
     * @param presetId Preset used for this message
     * @param msgType Type of message (DEPOSIT, WITHDRAWAL, BRIDGE) — bound into the hash to prevent cross-type collisions
     * @param destChainId Destination chain identifier — bound into the hash so the source-signed id self-authenticates the target chain
     * @return messageId Unique message identifier
     */
    function generateMessageId(
        uint256 sourceChainId,
        address sender,
        uint256 nonce,
        bytes memory payload,
        uint256 timestamp,
        bytes32 presetId,
        MessageType msgType,
        uint256 destChainId
    ) internal pure returns (bytes32) {
        return generateMessageId(
            sourceChainId, sender.addressToBytes32(), nonce, payload, timestamp, presetId, msgType, destChainId
        );
    }

    /**
     * @notice Generate unique message ID from bytes32 sender
     * @dev Used for both EVM (converted) and non-EVM (native bytes32) senders
     * @param sourceChainId Source chain identifier
     * @param sender Message sender as bytes32
     * @param nonce Sender's nonce
     * @param payload Message payload
     * @param timestamp Block timestamp
     * @param presetId Preset used for this message
     * @param msgType Type of message (DEPOSIT, WITHDRAWAL, BRIDGE) — bound into the hash to prevent cross-type collisions
     * @param destChainId Destination chain identifier — bound into the hash so the source-signed id self-authenticates the target chain
     * @return messageId Unique message identifier
     */
    function generateMessageId(
        uint256 sourceChainId,
        bytes32 sender,
        uint256 nonce,
        bytes memory payload,
        uint256 timestamp,
        bytes32 presetId,
        MessageType msgType,
        uint256 destChainId
    ) internal pure returns (bytes32) {
        return keccak256(
            abi.encodePacked(
                sourceChainId, sender, nonce, keccak256(payload), timestamp, presetId, msgType, destChainId
            )
        );
    }

    /**
     * @notice Encode a cross-chain message
     * @param message The message to encode
     * @return Encoded message bytes
     */
    function encodeMessage(CrossChainMessage memory message) internal pure returns (bytes memory) {
        return abi.encode(message);
    }

    /**
     * @notice Decode a cross-chain message
     * @param encodedMessage Encoded message bytes
     * @return message Decoded CrossChainMessage struct
     */
    function decodeMessage(bytes memory encodedMessage) internal pure returns (CrossChainMessage memory message) {
        (message) = abi.decode(encodedMessage, (CrossChainMessage));
    }

    /**
     * @notice Calculate retry delay based on attempt number (exponential backoff)
     * @param attemptNumber Current retry attempt
     * @return Delay in seconds before next retry
     */
    function getRetryDelay(uint256 attemptNumber) internal pure returns (uint256) {
        // 5 minutes * 2^attemptNumber (5m, 10m, 20m, 40m, 80m)
        return 5 minutes * (2 ** attemptNumber);
    }

    /**
     * @notice Validate message structure
     * @param message Message to validate
     * @return valid True if message is valid
     */
    function validateMessage(CrossChainMessage memory message) internal pure returns (bool valid) {
        return (message.messageId != bytes32(0) && message.sourceChainId != 0 && message.destChainId != 0
                && message.sourceChainId != message.destChainId && message.sender != bytes32(0)
                && message.payload.length > 0 && message.timestamp > 0);
    }
}

src/protocol/underlyingManager/SpokeUnderlyingManager.sol

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

import {ISpokeUnderlyingManager} from "./interfaces/ISpokeUnderlyingManager.sol";
import {UnderlyingManagerBase, ZeroAddress, ZeroAmount, AssetNotSupported} from "./UnderlyingManagerBase.sol";
import {IVault} from "../vault/interfaces/IVault.sol";
import {IIncomeCollector, RevenueSource} from "../incomeCollector/interfaces/IIncomeCollector.sol";
import {MessageType, MessageOrigin} from "../mba/libraries/MessageLib.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {WithdrawalRequest, WithdrawalRequestStatus} from "./interfaces/Types.sol";
import {AddressConversion} from "../mba/libraries/AddressConversion.sol";
import {Attestation} from "../attestation/AttestationTypes.sol";
import {IAttestationService} from "../attestation/interfaces/IAttestationService.sol";
import {QueuedRequestStatus, DrawResult, DrawStatus} from "../vault/Types.sol";

error WithdrawalNotFound();
error HubChainNotSet();
error WithdrawalRequestAlreadyExists();
error NotVault();
error NotRecipientOrAdmin();
error InvalidWithdrawalStatus();
error IncomeCollectorNotSet();

/**
 * @title SpokeUnderlyingManager
 * @author Clovis Protocol
 * @notice Underlying Manager deployed on Spoke chains
 * @dev Handles deposits to the Vault and sends messages to Hub for uToken minting
 * @dev Also handles withdrawal requests from Hub. Queuing is delegated to the Vault.
 * @dev 1 underlying token = 1 uToken (same decimals across all chains)
 */
abstract contract SpokeUnderlyingManager is ISpokeUnderlyingManager, UnderlyingManagerBase {
    using SafeERC20 for IERC20;

    using AddressConversion for bytes32;

    using AddressConversion for address;

    uint256 public immutable HUB_CHAIN_ID;

    IVault public immutable VAULT;

    /// @notice Mapping from withdraw ID to withdrawal request details
    mapping(uint256 => WithdrawalRequest) internal _withdrawalRequests;

    /// @notice Mapping from Vault queue ID to withdraw ID for callback lookup
    mapping(uint256 vaultQueueId => uint256 withdrawId) internal _vaultQueueIdToWithdrawId;

    /// @notice Accumulated preset fees per asset
    mapping(address => uint256) internal _collectedFees;

    /// @notice Income collector for fee distribution
    IIncomeCollector internal _incomeCollector;

    uint256[46] private __gap;

    /// @notice Modifier to ensure only the Vault can call a function
    modifier onlyVault() {
        if (msg.sender != address(VAULT)) revert NotVault();
        _;
    }

    constructor(uint256 hubChainId_, address vault_, address crossMessageController_, address accessControl_)
        UnderlyingManagerBase(crossMessageController_, accessControl_)
    {
        if (hubChainId_ == 0) revert HubChainNotSet();
        if (vault_ == address(0)) revert ZeroAddress();
        HUB_CHAIN_ID = hubChainId_;
        VAULT = IVault(vault_);
    }

    /// @inheritdoc ISpokeUnderlyingManager
    function deposit(Attestation calldata attestation, address asset, uint256 amount)
        external
        payable
        override
        nonReentrant
        whenNotPaused
        returns (uint256 depositId)
    {
        _attestationService.verify(attestation, msg.sender, address(this), msg.value, msg.data);
        return _deposit(asset, amount, msg.sender, address(0), bytes4(0), "", bytes32(0));
    }

    /// @inheritdoc ISpokeUnderlyingManager
    function deposit(Attestation calldata attestation, address asset, uint256 amount, bytes32 presetId)
        external
        payable
        override
        nonReentrant
        whenNotPaused
        returns (uint256 depositId)
    {
        _attestationService.verify(attestation, msg.sender, address(this), msg.value, msg.data);
        return _deposit(asset, amount, msg.sender, address(0), bytes4(0), "", presetId);
    }

    /// @inheritdoc ISpokeUnderlyingManager
    function depositFor(Attestation calldata attestation, address asset, uint256 amount, address recipient)
        external
        payable
        override
        nonReentrant
        whenNotPaused
        returns (uint256 depositId)
    {
        _attestationService.verify(attestation, msg.sender, address(this), msg.value, msg.data);
        if (recipient == address(0)) revert ZeroAddress();
        return _deposit(asset, amount, recipient, address(0), bytes4(0), "", bytes32(0));
    }

    /// @inheritdoc ISpokeUnderlyingManager
    function depositFor(
        Attestation calldata attestation,
        address asset,
        uint256 amount,
        address recipient,
        bytes32 presetId
    ) external payable override nonReentrant whenNotPaused returns (uint256 depositId) {
        _attestationService.verify(attestation, msg.sender, address(this), msg.value, msg.data);
        if (recipient == address(0)) revert ZeroAddress();
        return _deposit(asset, amount, recipient, address(0), bytes4(0), "", presetId);
    }

    /// @inheritdoc ISpokeUnderlyingManager
    function deposit(
        Attestation calldata attestation,
        address asset,
        uint256 amount,
        address hookTarget,
        bytes4 hookSelector,
        bytes calldata hookExtraData
    ) external payable override nonReentrant whenNotPaused returns (uint256 depositId) {
        _attestationService.verify(attestation, msg.sender, address(this), msg.value, msg.data);
        return _deposit(asset, amount, msg.sender, hookTarget, hookSelector, hookExtraData, bytes32(0));
    }

    /// @inheritdoc ISpokeUnderlyingManager
    function depositFor(
        Attestation calldata attestation,
        address asset,
        uint256 amount,
        address recipient,
        address hookTarget,
        bytes4 hookSelector,
        bytes calldata hookExtraData
    ) external payable override nonReentrant whenNotPaused returns (uint256 depositId) {
        _attestationService.verify(attestation, msg.sender, address(this), msg.value, msg.data);
        if (recipient == address(0)) revert ZeroAddress();
        return _deposit(asset, amount, recipient, hookTarget, hookSelector, hookExtraData, bytes32(0));
    }

    /// @inheritdoc ISpokeUnderlyingManager
    function deposit(
        Attestation calldata attestation,
        address asset,
        uint256 amount,
        address hookTarget,
        bytes4 hookSelector,
        bytes calldata hookExtraData,
        bytes32 presetId
    ) external payable override nonReentrant whenNotPaused returns (uint256 depositId) {
        _attestationService.verify(attestation, msg.sender, address(this), msg.value, msg.data);
        return _deposit(asset, amount, msg.sender, hookTarget, hookSelector, hookExtraData, presetId);
    }

    /// @inheritdoc ISpokeUnderlyingManager
    function depositFor(
        Attestation calldata attestation,
        address asset,
        uint256 amount,
        address recipient,
        address hookTarget,
        bytes4 hookSelector,
        bytes calldata hookExtraData,
        bytes32 presetId
    ) external payable override nonReentrant whenNotPaused returns (uint256 depositId) {
        _attestationService.verify(attestation, msg.sender, address(this), msg.value, msg.data);
        if (recipient == address(0)) revert ZeroAddress();
        return _deposit(asset, amount, recipient, hookTarget, hookSelector, hookExtraData, presetId);
    }

    /**
     * @notice Callback from Vault when a queued draw request is processed
     * @dev Only callable by the Vault. Updates local status based on Vault's outcome.
     * @param queueId The Vault's queue ID
     * @param recipient The actual recipient (may differ from original if redirected)
     * @param status The outcome: Fulfilled or Unfulfillable
     */
    function queuedDrawProcessed(uint256 queueId, address recipient, QueuedRequestStatus status)
        external
        override
        onlyVault
    {
        uint256 withdrawId = _vaultQueueIdToWithdrawId[queueId];
        WithdrawalRequest storage request = _withdrawalRequests[withdrawId];

        if (status == QueuedRequestStatus.Fulfilled) {
            request.status = WithdrawalRequestStatus.Fulfilled;
            emit WithdrawalRequestFulfilled(
                withdrawId, recipient, request.asset.bytes32ToAddress(), request.outputAmount
            );
        } else if (status == QueuedRequestStatus.Unfulfillable) {
            request.status = WithdrawalRequestStatus.Unfulfillable;
            emit WithdrawalRequestUnfulfillable(withdrawId);
        }
        // Note: Cancelled status is handled locally, not via callback
    }

    /**
     * @notice Cancel a withdrawal request and redeposit funds to Hub
     * @dev Caller must be the spoke-side recipient (EVM only), the original
     *      Hub-side initiator, or UM_ADMIN_ROLE. Status must be Queued or
     *      Unfulfillable for EVM recipients, or Pending for non-EVM (admin only).
     * @dev The redeposit always mints uTokens at `originalSender` — the
     *      Hub-chain address that initiated the withdrawal — regardless of
     *      `recipient`'s encoding. This closes CLOV-456 / GH #270.
     * @param attestation Attestation proving the transaction is authorized
     * @param withdrawId The withdrawal ID to cancel
     * @return depositId The deposit ID for the redeposit message
     */
    function cancelWithdrawalRequest(Attestation calldata attestation, uint256 withdrawId)
        external
        payable
        nonReentrant
        whenNotPaused
        returns (uint256 depositId)
    {
        _attestationService.verify(attestation, msg.sender, address(this), msg.value, msg.data);

        WithdrawalRequest storage request = _withdrawalRequests[withdrawId];

        _validateCancellation(request);

        // If queued in Vault, cancel there first
        if (request.vaultQueueId > 0) {
            VAULT.cancelQueuedDraw(request.vaultQueueId);
        }

        // Update status
        request.status = WithdrawalRequestStatus.Cancelled;

        // Send redeposit message to Hub (no token transfer - funds already in Vault)
        depositId = _sendDepositMessage(
            request.asset.bytes32ToAddress(),
            request.outputAmount,
            request.originalSender,
            address(0),
            bytes4(0),
            "",
            bytes32(0) // default preset
        );

        emit WithdrawalRequestCancelled(withdrawId);
        return depositId;
    }

    /**
     * @notice Drop a withdrawal request without redepositing funds
     * @dev Admin-only function for Pending requests (non-EVM recipients)
     * @dev Marks as Cancelled without triggering redeposit to Hub
     * @dev Funds remain in Vault allocated to this app
     * @param withdrawId The withdrawal ID from Hub
     */
    function dropWithdrawalRequest(uint256 withdrawId) external onlyRole(UM_ADMIN_ROLE) {
        WithdrawalRequest storage request = _withdrawalRequests[withdrawId];

        if (request.outputAmount == 0) revert WithdrawalNotFound();

        // Can only drop Pending requests (non-EVM recipients that can't be processed)
        if (request.status != WithdrawalRequestStatus.Pending) revert InvalidWithdrawalStatus();

        // Mark as Cancelled (logical delete without redeposit)
        request.status = WithdrawalRequestStatus.Cancelled;

        emit WithdrawalRequestCancelled(withdrawId);
    }

    /// @inheritdoc ISpokeUnderlyingManager
    function setIncomeCollector(address incomeCollector_) external onlyRole(UM_ADMIN_ROLE) {
        if (incomeCollector_ == address(0)) revert ZeroAddress();
        _incomeCollector = IIncomeCollector(incomeCollector_);
        emit IncomeCollectorSet(incomeCollector_);
    }

    /// @inheritdoc ISpokeUnderlyingManager
    function collectFees(address asset) external override nonReentrant {
        if (address(_incomeCollector) == address(0)) revert IncomeCollectorNotSet();

        uint256 fees = _collectedFees[asset];
        if (fees == 0) return;

        _collectedFees[asset] = 0;

        // Draw fees from Vault (they were supplied during deposit)
        VAULT.draw(asset, fees);

        // Approve and transfer to income collector
        IERC20(asset).forceApprove(address(_incomeCollector), fees);
        _incomeCollector.collectIncome(asset, fees, RevenueSource.OTHERS);

        emit FeesCollected(asset, fees, address(_incomeCollector));
    }

    /**
     * @notice Get the Vault this app is associated with
     * @return The Vault contract
     */
    function vault() external view override returns (IVault) {
        return VAULT;
    }

    /**
     * @notice Check if the Vault App is currently active
     * @return True if not paused, false otherwise
     */
    function isActive() external view override returns (bool) {
        return !paused();
    }

    /// @inheritdoc ISpokeUnderlyingManager
    function getWithdrawalRequest(uint256 requestId)
        external
        view
        override
        returns (bytes32 recipient, bytes32 asset, uint256 outputAmount, bool fulfilled, bool cancelled)
    {
        WithdrawalRequest memory request = _withdrawalRequests[requestId];
        bool isFulfilled = request.status == WithdrawalRequestStatus.Fulfilled;
        bool isCancelled = request.status == WithdrawalRequestStatus.Cancelled;
        return (request.recipient, request.asset, request.outputAmount, isFulfilled, isCancelled);
    }

    /**
     * @notice Get detailed withdrawal request information including status and vault queue ID
     * @param requestId The withdrawal request ID
     * @return request The full withdrawal request struct
     */
    function getWithdrawalRequestDetails(uint256 requestId) external view returns (WithdrawalRequest memory request) {
        return _withdrawalRequests[requestId];
    }

    /// @inheritdoc ISpokeUnderlyingManager
    function estimateDepositFee(address asset, uint256 amount, address recipient)
        external
        view
        override
        returns (uint256 totalFee, uint256[] memory adapterFees)
    {
        bytes memory payload = _encodeDepositPayload(0, asset, amount, recipient, address(0), bytes4(0), "");
        return CROSS_MESSAGE_CONTROLLER.estimateFees(HUB_CHAIN_ID, payload, MessageType.DEPOSIT);
    }

    /// @inheritdoc ISpokeUnderlyingManager
    function estimateDepositFee(
        address asset,
        uint256 amount,
        address recipient,
        address hookTarget,
        bytes4 hookSelector,
        bytes calldata hookExtraData
    ) external view override returns (uint256 totalFee, uint256[] memory adapterFees) {
        // Use depositId=0 as placeholder since it doesn't affect fee calculation
        bytes memory payload =
            _encodeDepositPayload(0, asset, amount, recipient, hookTarget, hookSelector, hookExtraData);
        return CROSS_MESSAGE_CONTROLLER.estimateFees(HUB_CHAIN_ID, payload, MessageType.DEPOSIT);
    }

    /// @inheritdoc ISpokeUnderlyingManager
    function estimateDepositFee(address asset, uint256 amount, address recipient, bytes32 presetId)
        external
        view
        override
        returns (uint256 totalFee, uint256[] memory adapterFees)
    {
        bytes memory payload = _encodeDepositPayload(0, asset, amount, recipient, address(0), bytes4(0), "");
        return CROSS_MESSAGE_CONTROLLER.estimateFees(HUB_CHAIN_ID, payload, MessageType.DEPOSIT, presetId);
    }

    /// @inheritdoc ISpokeUnderlyingManager
    function estimateDepositFee(
        address asset,
        uint256 amount,
        address recipient,
        address hookTarget,
        bytes4 hookSelector,
        bytes calldata hookExtraData,
        bytes32 presetId
    ) external view override returns (uint256 totalFee, uint256[] memory adapterFees) {
        bytes memory payload =
            _encodeDepositPayload(0, asset, amount, recipient, hookTarget, hookSelector, hookExtraData);
        return CROSS_MESSAGE_CONTROLLER.estimateFees(HUB_CHAIN_ID, payload, MessageType.DEPOSIT, presetId);
    }

    /// @inheritdoc ISpokeUnderlyingManager
    function estimateCancelWithdrawalRequestFee(uint256 withdrawId)
        external
        view
        override
        returns (uint256 totalFee, uint256[] memory adapterFees)
    {
        WithdrawalRequest storage request = _withdrawalRequests[withdrawId];
        // Build the redeposit payload using the withdrawal request details.
        // The redeposit target is `originalSender` (CLOV-456), not the
        // spoke-side `recipient`.
        address assetAddr = request.asset.bytes32ToAddress();
        bytes memory payload = _encodeDepositPayload(
            0, assetAddr, request.outputAmount, request.originalSender, address(0), bytes4(0), ""
        );
        return CROSS_MESSAGE_CONTROLLER.estimateFees(HUB_CHAIN_ID, payload, MessageType.DEPOSIT);
    }

    /// @inheritdoc ISpokeUnderlyingManager
    function getCollectedFees(address asset) external view returns (uint256) {
        return _collectedFees[asset];
    }

    /**
     * @notice Get the supported assets for this Vault App
     * @dev Returns an empty array - assets are managed via setAsset() and checked via isAssetSupported()
     * @return Empty array (use isAssetSupported to check individual assets)
     */
    function supportedAssets() external pure override returns (address[] memory) {
        // Note: The actual supported assets are tracked in _supportedAssets mapping
        // This returns empty as there's no enumerable list in storage
        return new address[](0);
    }

    /**
     * @notice Internal initialization logic
     */
    // forge-lint: disable-next-line(mixed-case-function)
    function __SpokeUnderlyingManager_init(address attestationService_) internal {
        if (attestationService_ == address(0)) revert ZeroAddress();
        _attestationService = IAttestationService(attestationService_);
    }

    /**
     * @notice Internal message handling for withdrawal requests from the Hub
     * @dev Called by base handleMessage() after authorization and age validation
     * @dev The messageId parameter is unused as replay protection is handled at the MBA layer
     */
    function _handleMessage(bytes32, bytes calldata payload, MessageOrigin calldata origin)
        internal
        override
        whenNotPaused
        returns (bool success)
    {
        (uint256 withdrawId, bytes32 asset, uint256 amount, bytes32 recipient, address originalSender) =
            _decodeWithdrawalPayload(payload);

        _processWithdrawalRequest(withdrawId, asset, amount, recipient, originalSender, origin);

        return true;
    }

    /**
     * @notice Internal deposit logic
     */
    function _deposit(
        address asset,
        uint256 amount,
        address recipient,
        address hookTarget,
        bytes4 hookSelector,
        bytes memory hookExtraData,
        bytes32 presetId
    ) internal returns (uint256 depositId) {
        if (asset == address(0)) revert ZeroAddress();
        if (amount == 0) revert ZeroAmount();
        if (!_supportedAssets[asset]) revert AssetNotSupported();

        // Transfer funds and supply to Vault
        IERC20(asset).safeTransferFrom(msg.sender, address(this), amount);
        IERC20(asset).forceApprove(address(VAULT), amount);
        VAULT.supply(asset, amount);

        // Apply preset fee — deduct from the amount sent in the deposit message
        // so Hub mints fewer uTokens; the fee remains as underlying in the Vault
        uint256 presetFee = _applyPresetFee(asset, amount, HUB_CHAIN_ID, presetId);
        uint256 netAmount = amount - presetFee;

        return _sendDepositMessage(asset, netAmount, recipient, hookTarget, hookSelector, hookExtraData, presetId);
    }

    /**
     * @notice Process a withdrawal request from the Hub
     * @dev Creates request with Pending status. For EVM recipients, calls Vault.draw() which may queue.
     * @dev Non-EVM recipients remain in Pending status and can only be cancelled by admin.
     */
    function _processWithdrawalRequest(
        uint256 withdrawId,
        bytes32 asset,
        uint256 outputAmount,
        bytes32 recipient,
        address originalSender,
        MessageOrigin calldata origin
    ) internal {
        if (outputAmount == 0) revert ZeroAmount();
        if (recipient == bytes32(0)) revert ZeroAddress();
        // `originalSender` is the Hub-side initiator and must be non-zero;
        // it is the cancel-path redeposit target so we never want a request
        // whose only refund channel mints to address(0).
        if (originalSender == address(0)) revert ZeroAddress();

        address assetAddr = asset.bytes32ToAddress();
        if (!_supportedAssets[assetAddr]) revert AssetNotSupported();

        if (_withdrawalRequests[withdrawId].recipient != bytes32(0)) revert WithdrawalRequestAlreadyExists();

        // Create request with Pending status
        _withdrawalRequests[withdrawId] = WithdrawalRequest({
            withdrawId: withdrawId,
            recipient: recipient,
            asset: asset,
            outputAmount: outputAmount,
            status: WithdrawalRequestStatus.Pending,
            vaultQueueId: 0,
            origin: origin,
            originalSender: originalSender
        });

        // Check if recipient is a valid EVM address
        if (!recipient.isValidEvmAddress()) {
            // Non-EVM recipient: keep Pending status, cannot interact with Vault queue
            // User can only be refunded via admin action (cancelWithdrawalRequest with UM_ADMIN_ROLE)
            emit WithdrawalRequestProcessed(
                withdrawId, 0, asset, outputAmount, recipient, WithdrawalRequestStatus.Pending
            );
            return;
        }

        // EVM recipient: attempt to draw from Vault
        address recipientAddr = recipient.bytes32ToAddress();

        // Call Vault.draw with queueOnInsolvency=true
        DrawResult memory result = VAULT.draw(assetAddr, outputAmount, recipientAddr, true);

        if (result.status == DrawStatus.Queued) {
            // Request was queued in Vault
            _withdrawalRequests[withdrawId].status = WithdrawalRequestStatus.Queued;
            _withdrawalRequests[withdrawId].vaultQueueId = result.queueId;
            _vaultQueueIdToWithdrawId[result.queueId] = withdrawId;

            emit WithdrawalRequestProcessed(
                withdrawId, result.queueId, asset, outputAmount, recipient, WithdrawalRequestStatus.Queued
            );
        } else if (result.status == DrawStatus.Fulfilled) {
            // Immediate fulfillment
            _withdrawalRequests[withdrawId].status = WithdrawalRequestStatus.Fulfilled;

            emit WithdrawalRequestFulfilled(withdrawId, recipientAddr, assetAddr, outputAmount);
        } else {
            // DrawStatus.Unfulfillable - transfer to recipient failed
            _withdrawalRequests[withdrawId].status = WithdrawalRequestStatus.Unfulfillable;

            emit WithdrawalRequestUnfulfillable(withdrawId);
        }
    }

    /**
     * @notice Send a deposit message to Hub to mint uTokens
     * @dev Used by both _deposit (after transferring funds) and cancelWithdrawalRequest (no transfer)
     * @param asset Asset address on this chain
     * @param amount Amount to deposit
     * @param recipient Recipient address for uTokens on Hub
     * @param hookTarget Optional hook target contract address
     * @param hookSelector Optional hook function selector
     * @param hookExtraData Optional extra data for the hook
     * @param presetId MBA preset to use (bytes32(0) = default)
     * @return depositId The unique deposit ID
     */
    function _sendDepositMessage(
        address asset,
        uint256 amount,
        address recipient,
        address hookTarget,
        bytes4 hookSelector,
        bytes memory hookExtraData,
        bytes32 presetId
    ) internal returns (uint256 depositId) {
        depositId = ++_depositNonce;

        bytes memory payload =
            _encodeDepositPayload(depositId, asset, amount, recipient, hookTarget, hookSelector, hookExtraData);

        (, uint256[] memory adapterValues) =
            CROSS_MESSAGE_CONTROLLER.estimateFees(HUB_CHAIN_ID, payload, MessageType.DEPOSIT, presetId);
        // TODO(audit-#210): replace the hardcoded 0 with the deposit's
        // USD-priced value (amount × oracle price) once OracleManager is
        // wired in (see CLOV-463 / issue #225). Until then the per-preset
        // maxUnderlyingValueUSD cap in SenderLogic is inert for this
        // dispatch — see https://github.com/Yei-Finance/clovis/issues/210.
        CROSS_MESSAGE_CONTROLLER.sendMessage{value: msg.value}(
            HUB_CHAIN_ID, payload, MessageType.DEPOSIT, adapterValues, presetId, 0
        );

        emit DepositInitiated(depositId, msg.sender, asset, amount, recipient);
    }

    /**
     * @notice Apply preset suggestedFeeBps to an amount
     * @param asset Asset address for fee collection
     * @param netAmount Amount to apply fee to
     * @param destChainId Destination chain ID
     * @param presetId Preset to read fee from (bytes32(0) = default)
     * @return presetFee Fee amount deducted
     */
    function _applyPresetFee(address asset, uint256 netAmount, uint256 destChainId, bytes32 presetId)
        internal
        returns (uint256 presetFee)
    {
        bytes32 resolvedPresetId =
            presetId == bytes32(0) ? CROSS_MESSAGE_CONTROLLER.getDefaultPreset(destChainId) : presetId;
        if (resolvedPresetId == bytes32(0)) return 0;
        uint256 presetFeeBps = CROSS_MESSAGE_CONTROLLER.getPresetFee(resolvedPresetId);
        if (presetFeeBps == 0) return 0;
        presetFee = (netAmount * presetFeeBps) / 10000;
        if (presetFee > 0) {
            _collectedFees[asset] += presetFee;
        }
    }

    /**
     * @notice Validate that a withdrawal request can be cancelled by the caller
     * @dev Checks authorization (recipient, original Hub-side sender, or admin)
     *      and status (Queued, Unfulfillable, or Pending for non-EVM).
     *      Either the spoke-side recipient or the Hub-side `originalSender`
     *      can cancel; in both cases the redeposit lands at `originalSender`
     *      on the Hub, so the recipient can only force a refund to the sender
     *      they were already trusting (no new attack surface).
     * @param request The withdrawal request to validate
     */
    function _validateCancellation(WithdrawalRequest storage request) internal view {
        bytes32 recipient = request.recipient;

        // Authorization check
        bool isEvmRecipient = recipient.isValidEvmAddress();
        bool isRecipient = isEvmRecipient && msg.sender == recipient.bytes32ToAddress();
        bool isOriginalSender = msg.sender == request.originalSender;
        bool isAdmin = ACCESS_CONTROL.hasRole(UM_ADMIN_ROLE, msg.sender);

        if (!isRecipient && !isOriginalSender && !isAdmin) revert NotRecipientOrAdmin();

        // Status check: Queued, Unfulfillable (for EVM) OR Pending with non-EVM recipient
        WithdrawalRequestStatus status = request.status;
        bool canCancelQueued = status == WithdrawalRequestStatus.Queued;
        bool canCancelUnfulfillable = status == WithdrawalRequestStatus.Unfulfillable;
        bool canCancelPendingNonEvm = status == WithdrawalRequestStatus.Pending && !isEvmRecipient;

        if (!canCancelQueued && !canCancelUnfulfillable && !canCancelPendingNonEvm) revert InvalidWithdrawalStatus();
    }

    /**
     * @notice Encode deposit payload for cross-chain message
     * @dev Converts address asset to bytes32 for Hub-side mapping lookup
     */
    function _encodeDepositPayload(
        uint256 depositId,
        address asset,
        uint256 amount,
        address recipient,
        address hookTarget,
        bytes4 hookSelector,
        bytes memory hookExtraData
    ) internal view returns (bytes memory) {
        bytes32 assetAsBytes32 = asset.addressToBytes32();
        return abi.encode(
            depositId, block.chainid, assetAsBytes32, amount, recipient, hookTarget, hookSelector, hookExtraData
        );
    }

    /**
     * @notice Decode withdrawal payload from cross-chain message
     */
    function _decodeWithdrawalPayload(bytes calldata payload)
        internal
        pure
        returns (uint256 withdrawId, bytes32 asset, uint256 amount, bytes32 recipient, address originalSender)
    {
        (withdrawId, asset, amount, recipient, originalSender) =
            abi.decode(payload, (uint256, bytes32, uint256, bytes32, address));
    }
}

src/protocol/underlyingManager/UnderlyingManagerBase.sol

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

import {IUnderlyingManager} from "./interfaces/IUnderlyingManager.sol";
import {MessageHandlerUpgradeable} from "../mba/handlers/MessageHandlerUpgradeable.sol";
import {IMessageHandler} from "../mba/interfaces/IMessageHandler.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {IAttestationService} from "../attestation/interfaces/IAttestationService.sol";
import {PauseRoles} from "../access/PauseRoles.sol";

error ZeroAddress();
error ZeroAmount();
error AssetNotSupported();
error InvalidPeer();
error ArrayLengthMismatch();
error InvalidChainId();
error SameChain();

/**
 * @title UnderlyingManagerBase
 * @author Clovis Protocol
 * @notice Abstract base contract for Underlying Managers on both Hub and Spoke chains
 * @dev Provides common functionality for cross-chain deposit/withdrawal messaging
 * @dev Implements IMessageHandler pattern for upgradeable contracts
 * @dev Assumes same asset has identical decimals across all supported chains
 */
abstract contract UnderlyingManagerBase is
    IUnderlyingManager,
    MessageHandlerUpgradeable,
    ReentrancyGuardTransient,
    Pausable
{
    using SafeERC20 for IERC20;

    bytes32 public constant UM_ADMIN_ROLE = keccak256("UM_ADMIN_ROLE");

    bytes32 public constant UM_MANAGER_ROLE = keccak256("UM_MANAGER_ROLE");

    /// @notice Pause-only role: gates `pause()`, and `pauseHooks()` on the Hub, never unpause or configuration
    bytes32 public constant UM_GUARDIAN_ROLE = keccak256("UM_GUARDIAN_ROLE");

    mapping(address => bool) internal _supportedAssets;

    uint256 internal _depositNonce;

    IAttestationService internal _attestationService;

    uint256[47] private __gap;

    constructor(address crossMessageController_, address accessControl_)
        MessageHandlerUpgradeable(crossMessageController_, accessControl_)
    {}

    /**
     * @notice Enable an asset for deposits/withdrawals
     * @param asset Address of the underlying asset
     */
    function setAsset(address asset, bool value) external onlyRole(UM_MANAGER_ROLE) {
        if (asset == address(0)) revert ZeroAddress();

        _supportedAssets[asset] = value;

        emit AssetSet(asset, value);
    }

    /**
     * @notice Pause the contract
     * @dev Only callable by UM_GUARDIAN_ROLE. Returns without effect when already paused, so a repeated or
     *      concurrent guardian call succeeds instead of reverting `EnforcedPause` (YEI-1006)
     */
    function pause() external onlyRole(UM_GUARDIAN_ROLE) {
        if (paused()) return;
        _pause();
    }

    /**
     * @notice Unpause the contract
     * @dev Only UNPAUSER_ROLE: the guardian pauses, the unpauser resumes (YEI-1006)
     */
    function unpause() external onlyRole(PauseRoles.UNPAUSER_ROLE) {
        _unpause();
    }

    /// @inheritdoc IUnderlyingManager
    function setAttestationService(address attestationService_) external override onlyRole(UM_ADMIN_ROLE) {
        if (attestationService_ == address(0)) revert ZeroAddress();
        _attestationService = IAttestationService(attestationService_);
        emit AttestationServiceSet(attestationService_);
    }

    /// @inheritdoc IUnderlyingManager
    function attestationService() external view override returns (IAttestationService) {
        return _attestationService;
    }

    /// @inheritdoc IUnderlyingManager
    function isAssetSupported(address asset) external view override returns (bool) {
        return _supportedAssets[asset];
    }

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId)
        public
        pure
        virtual
        override(MessageHandlerUpgradeable)
        returns (bool)
    {
        return interfaceId == type(IMessageHandler).interfaceId || interfaceId == type(IERC165).interfaceId
            || interfaceId == type(IUnderlyingManager).interfaceId;
    }
}

src/protocol/underlyingManager/interfaces/ISpokeUnderlyingManager.sol

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

import {IUnderlyingManager} from "./IUnderlyingManager.sol";
import {IVault} from "../../vault/interfaces/IVault.sol";
import {IVaultApp} from "../../vault/interfaces/IVaultApp.sol";
import {Attestation} from "../../attestation/AttestationTypes.sol";
import {WithdrawalRequestStatus} from "./Types.sol";

/**
 * @title ISpokeUnderlyingManager
 * @author Clovis Protocol
 * @notice Interface for Spoke chain Underlying Manager (handles deposits to Hub)
 * @dev Withdrawal queuing is delegated to the Vault contract for unified FIFO ordering
 */
interface ISpokeUnderlyingManager is IUnderlyingManager, IVaultApp {
    /**
     * @notice Emitted when a deposit is initiated
     * @param depositId Unique deposit identifier
     * @param depositor Address that initiated the deposit
     * @param asset Address of the deposited asset
     * @param amount Amount deposited
     * @param recipient Address to receive uTokens on the Hub
     */
    event DepositInitiated(
        uint256 indexed depositId, address indexed depositor, address indexed asset, uint256 amount, address recipient
    );

    /// @notice Emitted when a withdrawal request is queued or marked pending
    /// @dev Only emitted when status is Queued or Pending, NOT when immediately fulfilled
    /// @param withdrawId The withdrawal ID from Hub
    /// @param vaultQueueId The Vault's queue ID (0 if non-EVM/Pending)
    /// @param asset The asset address as bytes32
    /// @param amount The amount to withdraw
    /// @param recipient The recipient address as bytes32
    /// @param status The current status of the request (Queued or Pending only)
    event WithdrawalRequestProcessed(
        uint256 indexed withdrawId,
        uint256 indexed vaultQueueId,
        bytes32 indexed asset,
        uint256 amount,
        bytes32 recipient,
        WithdrawalRequestStatus status
    );

    /// @notice Emitted when a withdrawal request is fulfilled (immediate or from queue)
    /// @param withdrawId The withdrawal ID
    /// @param recipient The actual recipient who received the funds (EVM address)
    /// @param asset The asset transferred (EVM address since transfer succeeded)
    /// @param amount The amount transferred
    event WithdrawalRequestFulfilled(uint256 indexed withdrawId, address recipient, address asset, uint256 amount);

    /// @notice Emitted when a withdrawal request becomes unfulfillable
    /// @param withdrawId The withdrawal ID
    event WithdrawalRequestUnfulfillable(uint256 indexed withdrawId);

    /// @notice Emitted when a withdrawal request is cancelled
    /// @param withdrawId The withdrawal ID
    event WithdrawalRequestCancelled(uint256 indexed withdrawId);

    /// @notice Emitted when preset fees are collected and sent to the income collector
    /// @param asset The asset that was collected
    /// @param amount The amount of fees collected
    /// @param collector The income collector address
    event FeesCollected(address indexed asset, uint256 amount, address indexed collector);

    /// @notice Emitted when the income collector is set
    /// @param incomeCollector The income collector address
    event IncomeCollectorSet(address indexed incomeCollector);

    /**
     * @notice Initialize the SpokeUnderlyingManager
     * @param attestationService_ Address of the attestation service contract
     */
    function initialize(address attestationService_) external;

    /**
     * @notice Deposit underlying assets to receive uTokens on the Hub chain
     * @param attestation Attestation proving the transaction is authorized
     * @param asset Address of the underlying asset to deposit
     * @param amount Amount to deposit
     * @return depositId Unique identifier for this deposit
     */
    function deposit(Attestation calldata attestation, address asset, uint256 amount)
        external
        payable
        returns (uint256 depositId);

    /**
     * @notice Deposit underlying assets with explicit preset
     * @param attestation Attestation proving the transaction is authorized
     * @param asset Address of the underlying asset to deposit
     * @param amount Amount to deposit
     * @param presetId MBA preset to use (bytes32(0) = default)
     * @return depositId Unique identifier for this deposit
     */
    function deposit(Attestation calldata attestation, address asset, uint256 amount, bytes32 presetId)
        external
        payable
        returns (uint256 depositId);

    /**
     * @notice Deposit underlying assets on behalf of a recipient
     * @param attestation Attestation proving the transaction is authorized
     * @param asset Address of the underlying asset to deposit
     * @param amount Amount to deposit
     * @param recipient Address to receive uTokens on the Hub
     * @return depositId Unique identifier for this deposit
     */
    function depositFor(Attestation calldata attestation, address asset, uint256 amount, address recipient)
        external
        payable
        returns (uint256 depositId);

    /**
     * @notice Deposit underlying assets on behalf of a recipient with explicit preset
     * @param attestation Attestation proving the transaction is authorized
     * @param asset Address of the underlying asset to deposit
     * @param amount Amount to deposit
     * @param recipient Address to receive uTokens on the Hub
     * @param presetId MBA preset to use (bytes32(0) = default)
     * @return depositId Unique identifier for this deposit
     */
    function depositFor(
        Attestation calldata attestation,
        address asset,
        uint256 amount,
        address recipient,
        bytes32 presetId
    ) external payable returns (uint256 depositId);

    /**
     * @notice Deposit underlying assets to receive uTokens on the Hub chain
     * @param attestation Attestation proving the transaction is authorized
     * @param asset Address of the underlying asset to deposit
     * @param amount Amount to deposit
     * @param hookTarget Allowlisted target contract for the hook
     * @param hookSelector Function selector to call on the hook target
     * @param hookExtraData Additional data to pass to the hook
     * @return depositId Unique identifier for this deposit
     */
    function deposit(
        Attestation calldata attestation,
        address asset,
        uint256 amount,
        address hookTarget,
        bytes4 hookSelector,
        bytes calldata hookExtraData
    ) external payable returns (uint256 depositId);

    /**
     * @notice Deposit underlying assets on behalf of a recipient
     * @param attestation Attestation proving the transaction is authorized
     * @param asset Address of the underlying asset to deposit
     * @param amount Amount to deposit
     * @param recipient Address to receive uTokens on the Hub
     * @param hookTarget Allowlisted target contract for the hook
     * @param hookSelector Function selector to call on the hook target
     * @param hookExtraData Additional data to pass to the hook
     * @return depositId Unique identifier for this deposit
     */
    function depositFor(
        Attestation calldata attestation,
        address asset,
        uint256 amount,
        address recipient,
        address hookTarget,
        bytes4 hookSelector,
        bytes calldata hookExtraData
    ) external payable returns (uint256 depositId);

    /**
     * @notice Deposit underlying assets with hooks and explicit preset
     * @param attestation Attestation proving the transaction is authorized
     * @param asset Address of the underlying asset to deposit
     * @param amount Amount to deposit
     * @param hookTarget Allowlisted target contract for the hook
     * @param hookSelector Function selector to call on the hook target
     * @param hookExtraData Additional data to pass to the hook
     * @param presetId Source preset to use for cross-chain message (bytes32(0) = default)
     * @return depositId Unique identifier for this deposit
     */
    function deposit(
        Attestation calldata attestation,
        address asset,
        uint256 amount,
        address hookTarget,
        bytes4 hookSelector,
        bytes calldata hookExtraData,
        bytes32 presetId
    ) external payable returns (uint256 depositId);

    /**
     * @notice Deposit underlying assets on behalf of a recipient with hooks and explicit preset
     * @param attestation Attestation proving the transaction is authorized
     * @param asset Address of the underlying asset to deposit
     * @param amount Amount to deposit
     * @param recipient Address to receive uTokens on the Hub
     * @param hookTarget Allowlisted target contract for the hook
     * @param hookSelector Function selector to call on the hook target
     * @param hookExtraData Additional data to pass to the hook
     * @param presetId Source preset to use for cross-chain message (bytes32(0) = default)
     * @return depositId Unique identifier for this deposit
     */
    function depositFor(
        Attestation calldata attestation,
        address asset,
        uint256 amount,
        address recipient,
        address hookTarget,
        bytes4 hookSelector,
        bytes calldata hookExtraData,
        bytes32 presetId
    ) external payable returns (uint256 depositId);

    /**
     * @notice Cancel a withdrawal request and redeposit funds to Hub
     * @dev For EVM recipients: caller must be the recipient and status must be Queued or Unfulfillable
     * @dev For non-EVM recipients: caller must have UM_ADMIN_ROLE and status must be Pending
     * @dev If request was queued in Vault, calls Vault.cancelQueuedDraw first
     * @param attestation Attestation proving the transaction is authorized
     * @param withdrawId The withdrawal ID from Hub
     * @return depositId The deposit ID for the redeposit message
     */
    function cancelWithdrawalRequest(Attestation calldata attestation, uint256 withdrawId)
        external
        payable
        returns (uint256 depositId);

    /**
     * @notice Drop a withdrawal request without redepositing funds
     * @dev Admin-only function for Pending requests (non-EVM recipients)
     * @dev Marks as Cancelled without triggering redeposit to Hub
     * @dev Funds remain in Vault allocated to this app
     * @param withdrawId The withdrawal ID from Hub
     */
    function dropWithdrawalRequest(uint256 withdrawId) external;

    /**
     * @notice Collect accumulated preset fees and send to IncomeCollector
     * @param asset The asset to collect fees for
     */
    function collectFees(address asset) external;

    /**
     * @notice Set the income collector address
     * @param incomeCollector_ Address of the income collector
     */
    function setIncomeCollector(address incomeCollector_) external;

    /**
     * @notice Get the Vault address
     * @return The Vault contract
     */
    function VAULT() external view returns (IVault);

    /**
     * @notice Get the Hub chain ID
     * @return Chain ID of the Hub
     */
    function HUB_CHAIN_ID() external view returns (uint256);

    /**
     * @notice Get withdrawal request information
     * @param requestId The request ID to query
     * @return recipient Address to receive the funds (bytes32 for non-EVM support)
     * @return asset Address of the asset
     * @return outputAmount Amount to be withdrawn
     * @return fulfilled True if the withdrawal has been fulfilled
     * @return cancelled True if the withdrawal was cancelled (redeposited)
     */
    function getWithdrawalRequest(uint256 requestId)
        external
        view
        returns (bytes32 recipient, bytes32 asset, uint256 outputAmount, bool fulfilled, bool cancelled);

    /**
     * @notice Estimate the cross-chain fee for a deposit
     * @param asset The asset to deposit
     * @param amount The amount to deposit
     * @param recipient The recipient address on Hub chain
     * @return totalFee Total fee in native token
     * @return adapterFees Individual fees per messaging adapter
     */
    function estimateDepositFee(address asset, uint256 amount, address recipient)
        external
        view
        returns (uint256 totalFee, uint256[] memory adapterFees);

    /**
     * @notice Estimate the cross-chain fee for a deposit with hook
     * @param asset The asset to deposit
     * @param amount The amount to deposit
     * @param recipient The recipient address on Hub chain
     * @param hookTarget Allowlisted target contract for the hook
     * @param hookSelector Function selector to call on the hook target
     * @param hookExtraData Additional data to pass to the hook
     * @return totalFee Total fee in native token
     * @return adapterFees Individual fees per messaging adapter
     */
    function estimateDepositFee(
        address asset,
        uint256 amount,
        address recipient,
        address hookTarget,
        bytes4 hookSelector,
        bytes calldata hookExtraData
    ) external view returns (uint256 totalFee, uint256[] memory adapterFees);

    /**
     * @notice Estimate the cross-chain fee for a deposit with explicit preset
     * @param asset The asset to deposit
     * @param amount The amount to deposit
     * @param recipient The recipient address on Hub chain
     * @param presetId MBA preset to use (bytes32(0) = default)
     * @return totalFee Total fee in native token
     * @return adapterFees Individual fees per messaging adapter
     */
    function estimateDepositFee(address asset, uint256 amount, address recipient, bytes32 presetId)
        external
        view
        returns (uint256 totalFee, uint256[] memory adapterFees);

    /**
     * @notice Estimate the cross-chain fee for a deposit with hook and explicit preset
     * @param asset The asset to deposit
     * @param amount The amount to deposit
     * @param recipient The recipient address on Hub chain
     * @param hookTarget Allowlisted target contract for the hook
     * @param hookSelector Function selector to call on the hook target
     * @param hookExtraData Additional data to pass to the hook
     * @param presetId MBA preset to use (bytes32(0) = default)
     * @return totalFee Total fee in native token
     * @return adapterFees Individual fees per messaging adapter
     */
    function estimateDepositFee(
        address asset,
        uint256 amount,
        address recipient,
        address hookTarget,
        bytes4 hookSelector,
        bytes calldata hookExtraData,
        bytes32 presetId
    ) external view returns (uint256 totalFee, uint256[] memory adapterFees);

    /**
     * @notice Estimate the cross-chain fee for cancelling a withdrawal request
     * @dev The cancellation sends a redeposit message to Hub to remint uTokens
     * @param withdrawId The withdrawal ID to cancel
     * @return totalFee Total fee in native token
     * @return adapterFees Individual fees per messaging adapter
     */
    function estimateCancelWithdrawalRequestFee(uint256 withdrawId)
        external
        view
        returns (uint256 totalFee, uint256[] memory adapterFees);

    /**
     * @notice Get accumulated preset fees for an asset
     * @param asset The asset to query
     * @return The accumulated fee amount
     */
    function getCollectedFees(address asset) external view returns (uint256);
}

src/protocol/underlyingManager/interfaces/IUnderlyingManager.sol

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

import {IAttestationService} from "../../attestation/interfaces/IAttestationService.sol";

/**
 * @title IUnderlyingManager
 * @author Clovis Protocol
 * @notice Interface for Underlying Manager contracts that handle deposits and withdrawals across chains
 * @dev 1 underlying token = 1 uToken (same decimals across all chains)
 */
interface IUnderlyingManager {
    /**
     * @notice Emitted when an asset is enabled
     * @param asset Address of the underlying asset
     */
    event AssetSet(address indexed asset, bool value);

    /**
     * @notice Emitted when the attestation service is updated
     * @param attestationService Address of the new attestation service
     */
    event AttestationServiceSet(address indexed attestationService);

    /**
     * @notice Set an asset for deposits/withdrawals
     * @param asset Address of the underlying asset
     * @param value True if the asset is supported, false if it is not
     */
    function setAsset(address asset, bool value) external;

    /**
     * @notice Update the attestation service
     * @param attestationService_ Address of the new attestation service
     */
    function setAttestationService(address attestationService_) external;

    /**
     * @notice Check if an asset is supported
     * @param asset Address of the underlying asset
     * @return True if the asset is supported
     */
    function isAssetSupported(address asset) external view returns (bool);

    /**
     * @notice Get the attestation service address
     * @return The attestation service contract
     */
    function attestationService() external view returns (IAttestationService);
}

src/protocol/underlyingManager/interfaces/Types.sol

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

import {MessageOrigin} from "../../mba/libraries/MessageLib.sol";

/// @notice Status of a withdrawal request in SpokeUnderlyingManager
/// @dev Pending: Just received OR non-EVM recipient awaiting admin action
/// @dev Queued: Request is queued in the Vault (EVM recipient only)
/// @dev Fulfilled: Successfully fulfilled
/// @dev Cancelled: Cancelled by user (funds redeposited to Hub)
/// @dev Unfulfillable: Transfer to recipient failed; awaiting admin redirect via Vault
enum WithdrawalRequestStatus {
    Pending,
    Queued,
    Fulfilled,
    Cancelled,
    Unfulfillable
}

/// @notice A withdrawal request received from the Hub
/// @param withdrawId The unique withdrawal ID from Hub
/// @param outputAmount The amount to withdraw
/// @param asset The asset address as bytes32 (for cross-chain compatibility)
/// @param recipient The recipient address as bytes32 (for non-EVM support)
/// @param status Current status of the request
/// @param vaultQueueId The Vault's queue ID (0 if not queued in Vault or non-EVM)
/// @param origin The message origin containing source chain info
/// @param originalSender The Hub-chain msg.sender that initiated the withdrawal;
///        used as the redeposit target on cancel so funds always return to a
///        Hub address the user controls regardless of `recipient`'s encoding
struct WithdrawalRequest {
    uint256 withdrawId;
    uint256 outputAmount;
    bytes32 asset;
    bytes32 recipient;
    WithdrawalRequestStatus status;
    uint256 vaultQueueId;
    MessageOrigin origin;
    address originalSender;
}

struct DepositSource {
    address uToken;
    uint256 amount;
    address recipient;
    uint256 depositId;
    uint256 sourceChainId;
}

struct ProcessDepositParams {
    uint256 sourceDepositId;
    uint256 sourceChainId;
    bytes32 sourcePeer;
    bytes32 underlyingAsset;
    uint256 sourceAmount;
    address recipient;
    address hookTarget;
    bytes4 hookSelector;
    bytes hookExtraData;
}

src/protocol/vault/Types.sol

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

/// @notice Status of a queued draw request in the Vault
enum QueuedRequestStatus {
    Pending,
    Fulfilled,
    Cancelled,
    Unfulfillable
}

/// @notice Status of a draw operation
enum DrawStatus {
    Fulfilled, // Transfer completed successfully
    Queued, // Request added to queue (insufficient liquidity)
    Unfulfillable // Transfer to recipient failed
}

/// @notice A queued draw request stored in the Vault
/// @param caller The VaultApp that initiated the draw request
/// @param asset The asset being drawn
/// @param amount The amount to draw
/// @param recipient The address that will receive the funds
/// @param status Current status of the request
/// @param timestamp Creation time of the request; used to gate same-window draw-cap restoration on
///        cancel / queued-unfulfillable (CLOV-667). Appended to a mapping-stored struct, so this is
///        upgrade-safe (the struct lives under a hashed slot location, no layout collision).
struct QueuedRequest {
    address caller;
    address asset;
    uint256 amount;
    address recipient;
    QueuedRequestStatus status;
    uint48 timestamp;
}

/// @notice Result returned from draw() function
/// @param queueId The queue ID (only meaningful when status=Queued)
/// @param status The outcome of the draw operation
struct DrawResult {
    uint256 queueId;
    DrawStatus status;
}

/// @notice Result returned from fulfillNext() and batchFulfill() functions
/// @param totalAmount Total amount fulfilled across all processed requests
/// @param fulfilledCount Number of requests successfully fulfilled
/// @param unfulfillableCount Number of requests marked as unfulfillable
/// @param unfulfillableAmount Total amount from unfulfillable requests
struct FulfillResult {
    uint256 totalAmount;
    uint256 fulfilledCount;
    uint256 unfulfillableCount;
    uint256 unfulfillableAmount;
}

src/protocol/vault/interfaces/ClovisTypes.sol

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

/*//////////////////////////////////////////////////////////////
                        VAULT TYPES
//////////////////////////////////////////////////////////////*/

/**
 * @notice Type of cap being modified for Vault Apps
 */
enum CapType {
    DRAW,
    SUPPLY
}

/**
 * @notice Configuration for a Vault App
 * @dev The per-app asset allowlist is the set of assets with `_appCaps[app][asset].windowDuration != 0`
 * (i.e. assets the Curator has explicitly configured caps for). There is no separate
 * `supportedAssets` field on this struct.
 * @param active Whether the Vault App is currently active
 */
struct AppConfig {
    bool active;
}

/**
 * @notice Rate-based cap for a single operation type (draw or supply)
 * @param maxPerWindow Maximum amount allowed per window (0 = blocked, type(uint256).max = unlimited)
 * @param consumed Amount consumed in the current window
 * @param windowStart Timestamp when the current window began
 * @param windowDuration Window length in seconds
 */
struct RateCap {
    uint256 maxPerWindow;
    uint256 consumed;
    uint48 windowStart;
    uint48 windowDuration;
}

/**
 * @notice Caps for Vault App operations (rate-based)
 * @param draw Rate cap for draw operations
 * @param supply Rate cap for supply operations
 */
struct AppCaps {
    RateCap draw;
    RateCap supply;
}

/**
 * @notice Configuration for an Adapter
 * @param supportedAssets Array of asset addresses the Adapter can manage
 * @param active Whether the Adapter is currently active
 */
struct AdapterConfig {
    address[] supportedAssets;
    bool active;
}

/**
 * @notice Caps for Adapter operations
 * @param maxAllocation Maximum allocation allowed for this adapter
 */
struct AdapterCaps {
    uint256 maxAllocation;
}

/**
 * @notice Information about an adapter for a specific asset
 * @param adapter Address of the adapter
 * @param asset Address of the asset
 * @param principal Principal amount deposited (0 if adapter doesn't support getPrincipal)
 * @param realAssets Current real asset value including gains/losses
 * @param allocationCap Remaining allocation capacity (type(uint256).max for no cap)
 * @param isLiquid Whether this is a liquid adapter
 * @param name Human-readable name of the adapter
 */
struct AdapterInfo {
    address adapter;
    address asset;
    uint256 principal;
    uint256 realAssets;
    uint256 allocationCap;
    bool isLiquid;
    string name;
}

/*//////////////////////////////////////////////////////////////
                        ORACLE TYPES
//////////////////////////////////////////////////////////////*/

/**
 * @notice Price payload for pull-mode oracle updates
 * @param payload Encoded price data from the oracle provider
 * @param provider Hash identifying the provider and price strategy (e.g., keccak256("CHAINLINK_PULL_V8"))
 */
struct PricePayload {
    bytes payload;
    bytes32 provider;
}

/**
 * @notice Oracle source configuration
 * @param oracle Address of the oracle contract
 * @param sourceHash Hash identifying the source
 * @param sourceSymbol Human-readable source identifier
 */
struct OracleSource {
    address oracle;
    bytes32 sourceHash;
    string sourceSymbol;
}

src/protocol/vault/interfaces/IVault.sol

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

import {AppConfig, AppCaps, AdapterCaps, AdapterInfo, CapType} from "./ClovisTypes.sol";
import {QueuedRequest, DrawResult, FulfillResult} from "../Types.sol";

/**
 * @title IVault
 * @notice Interface for the Vault contract that manages multiple underlying assets,
 * Vault Apps, and investment Adapters across Spoke chains
 * @dev One Vault contract manages several underlying assets and Adapters, holding funds for Vault Apps
 */
interface IVault {
    /// @notice Emitted when a Vault App's active flag is set
    /// @param app The Vault App address
    /// @param active Whether the Vault App is active
    event VaultAppUpdated(address indexed app, bool active);

    event VaultAppCapsUpdated(
        address indexed app,
        address indexed asset,
        CapType capType,
        uint256 capAmount,
        uint48 windowDuration,
        string symbol,
        uint8 decimals
    );

    event AdapterConfigUpdated(address indexed adapter, address indexed asset, bool active, string name);

    event AdapterAllocationCapUpdated(address indexed adapter, address indexed asset, uint256 capAmount);

    /// @notice Emitted when a per-asset Vault stock cap (holdings ceiling) is set.
    /// @param asset The underlying asset.
    /// @param capAmount The new holdings ceiling (0 = deposits blocked, type(uint256).max = unlimited).
    event VaultStockCapUpdated(address indexed asset, uint256 capAmount);

    event Supply(address indexed app, address indexed asset, uint256 amount);

    event Allocated(address indexed adapter, address indexed asset, uint256 amount);

    event Deallocated(address indexed adapter, address indexed asset, uint256 amount);

    event DeallocationPrepared(address indexed adapter, address indexed asset);

    event LiquidAdapterUpdated(address indexed adapter, address indexed asset, bool active);

    /// @notice Emitted on `supply` when the aggregate liquid-adapter capacity for `asset` was
    /// insufficient to absorb the full amount and `residual` stayed idle in the Vault.
    /// @dev Fires only if at least one wei was left over after walking the liquid-adapter set.
    /// @param asset The asset being supplied
    /// @param residual The residual amount that stayed idle in the Vault
    event LiquidAllocationFellThrough(address indexed asset, uint256 residual);

    /// @notice Emitted when a liquid-adapter `allocate` leg reverted and was skipped during supply.
    /// @dev The atomic `allocateLegCore` self-call rolled back the pre-allocate transfer, so no funds
    /// are stranded in the adapter; the amount falls through to idle (and may trigger
    /// `LiquidAllocationFellThrough`). Surfaced for operator detection of a paused/capped adapter.
    /// @param adapter The liquid adapter whose `allocate` reverted
    /// @param asset The asset being allocated
    /// @param amount The amount that was skipped for this adapter
    event AdapterAllocateFailed(address indexed adapter, address indexed asset, uint256 amount);

    /// @notice Emitted when a liquid-adapter `deallocate` leg reverted and was skipped during a draw or fulfill.
    /// @dev The `deallocate` is called before the pull, so a revert leaks nothing; the loop continues to the
    /// next adapter. If the aggregate falls short the caller demotes the request (Queued/Unfulfillable),
    /// it does not revert. Surfaced for operator detection of a paused adapter.
    /// @param adapter The liquid adapter whose `deallocate` reverted
    /// @param asset The asset being deallocated
    /// @param amount The amount that was skipped for this adapter
    event AdapterDeallocateFailed(address indexed adapter, address indexed asset, uint256 amount);

    /// @notice Emitted when funds are drawn from the Vault
    /// @param app The VaultApp that initiated the draw
    /// @param asset The asset being drawn
    /// @param amount The amount drawn
    /// @param recipient The recipient of the funds
    /// @param queueId The queue ID (0 if immediate fulfillment, >0 if from queue)
    event Draw(address indexed app, address indexed asset, uint256 amount, address recipient, uint256 queueId);

    /// @notice Emitted when a draw request is queued due to insufficient liquidity
    /// @param queueId The unique queue ID for this request
    /// @param caller The VaultApp that initiated the draw
    /// @param asset The asset being drawn
    /// @param amount The amount requested
    /// @param recipient The intended recipient of the funds
    event DrawQueued(
        uint256 indexed queueId, address indexed caller, address indexed asset, uint256 amount, address recipient
    );

    /// @notice Emitted when a queued draw request is cancelled
    /// @param queueId The queue ID of the cancelled request
    /// @param caller The VaultApp that initiated the original draw
    /// @param asset The asset that was requested
    /// @param amount The amount that was requested
    /// @param recipient The intended recipient
    event QueuedDrawCancelled(
        uint256 indexed queueId, address indexed caller, address indexed asset, uint256 amount, address recipient
    );

    /// @notice Emitted when a queued draw request cannot be fulfilled (transfer to recipient failed)
    /// @param queueId The queue ID of the unfulfillable request
    /// @param caller The VaultApp that initiated the draw
    /// @param asset The asset that was requested
    /// @param amount The amount that was requested
    /// @param recipient The recipient whose transfer failed
    event QueuedDrawUnfulfillable(
        uint256 indexed queueId, address indexed caller, address indexed asset, uint256 amount, address recipient
    );

    /// @notice Emitted when an unfulfillable request is redirected to a new recipient
    /// @param queueId The queue ID of the redirected request
    /// @param asset The asset being transferred
    /// @param originalRecipient The original recipient whose transfer failed
    /// @param newRecipient The new recipient
    event QueuedDrawRedirected(
        uint256 indexed queueId, address indexed asset, address originalRecipient, address newRecipient
    );

    /// @notice Emitted when an immediate draw cannot be fulfilled (transfer to recipient failed)
    /// @param caller The VaultApp that initiated the draw
    /// @param asset The asset that was requested
    /// @param amount The amount that was requested
    /// @param recipient The recipient whose transfer failed
    event DrawUnfulfillable(address indexed caller, address indexed asset, uint256 amount, address recipient);

    /// @notice Emitted when a Vault Admin emergency-withdraws stranded funds from the Vault
    /// @param asset The asset withdrawn
    /// @param recipient The recipient of the withdrawn funds
    /// @param amount The amount withdrawn
    event EmergencyWithdraw(address indexed asset, address indexed recipient, uint256 amount);

    /**
     * @notice Initialize the Vault contract
     * @param initialAdmin The address of the initial admin
     */
    function initialize(address initialAdmin) external;

    /**
     * @notice Set whether a Vault App is active
     * @dev Only `VAULT_CURATOR_ROLE` can call. The per-app asset allowlist is managed
     * implicitly through `setAppCaps` — an asset becomes drawable/suppliable for `app`
     * once a cap with non-zero `windowDuration` is configured for it.
     *
     * Post-upgrade migration: removing `supportedAssets` from `AppConfig` (CLOV-487)
     * shifts `active` from per-mapping-entry storage offset+1 to offset+0, which
     * aliases the legacy array's length slot. Pre-upgrade entries with a non-empty
     * `supportedAssets` array silently read as `active=true` post-upgrade — including
     * apps the Curator had deactivated. For each chain already running the older
     * `AppConfig` shape, call this function once per previously-registered app with
     * the intended post-upgrade `active` value to explicitly write the bool at the
     * new offset. Apps registered post-upgrade do not need migration.
     * @param app Address of the Vault App
     * @param active Whether the Vault App should be active
     */
    function setVaultAppActive(address app, bool active) external;

    /**
     * @notice Set the draw or supply cap for a Vault App with custom window duration
     * @param app Address of the Vault App
     * @param asset Address of the asset
     * @param cap Type of cap to set (DRAW or SUPPLY)
     * @param amount Max amount per window (in asset decimals)
     * @param windowDuration Window length in seconds (must be > 0)
     */
    function setAppCaps(address app, address asset, CapType cap, uint256 amount, uint48 windowDuration) external;

    /**
     * @notice Set or remove an adapter for an asset
     * @dev Only curators can add or remove adapters
     * @param adapter Address of the Adapter
     * @param asset Address of the asset
     * @param active Whether the Adapter should be active for this asset
     */
    function setAdapterConfig(address adapter, address asset, bool active) external;

    /**
     * @notice Set the maximum allocation cap for an Adapter
     * @dev Only curators can set allocation caps
     * @param adapter Address of the Adapter
     * @param asset Address of the asset
     * @param amount Cap amount
     */
    function setAdapterAllocationCap(address adapter, address asset, uint256 amount) external;

    /// @notice Set the per-asset stock cap (ceiling on total Vault holdings of `asset`).
    /// @dev Requires VAULT_CURATOR_ROLE. `amount == 0` blocks all deposits for the asset
    ///      (fail-closed); use type(uint256).max for unlimited.
    /// @param asset The underlying asset.
    /// @param amount The holdings ceiling in the asset's native decimals.
    function setVaultStockCap(address asset, uint256 amount) external;

    /**
     * @notice Supply funds from a Vault App to the Vault
     * @dev Only active Vault Apps can call. Automatically sends deposits to LiquidAdapters
     * Must check supply caps. Only supports non-rebasing assets.
     * @param asset Address of the asset being supplied
     * @param amount Amount to supply (must equal ERC20 transfer amount)
     */
    function supply(address asset, uint256 amount) external;

    /**
     * @notice Draw funds from the Vault to the calling Vault App (reverts on insufficient liquidity)
     * @dev Only active Vault Apps can call. Must check draw caps.
     * Only supports non-rebasing assets. Transfers to msg.sender.
     * @param asset Address of the asset being drawn
     * @param amount Amount to draw (must equal ERC20 transfer amount)
     * @return result DrawResult with queueId=0 and status=Fulfilled (or Unfulfillable if transfer fails)
     */
    function draw(address asset, uint256 amount) external returns (DrawResult memory result);

    /**
     * @notice Draw funds from the Vault with recipient and queue option
     * @dev Only active Vault Apps can call. Must check draw caps.
     * If queueOnInsolvency is true and insufficient liquidity, request is queued.
     * If queueOnInsolvency is false and insufficient liquidity, reverts.
     * @param asset Address of the asset being drawn
     * @param amount Amount to draw
     * @param recipient Address to receive the funds
     * @param queueOnInsolvency If true, queue on insufficient liquidity; if false, revert
     * @return result DrawResult with queueId (>0 if queued) and status
     */
    function draw(address asset, uint256 amount, address recipient, bool queueOnInsolvency)
        external
        returns (DrawResult memory result);

    /**
     * @notice Cancel a queued draw request
     * @dev Only the original caller (VaultApp) can cancel. Request must be Pending or
     * Unfulfillable. The Unfulfillable case is the recovery path for end users whose
     * recipient transfer failed during fulfillment (e.g., USDC blacklist), letting
     * the upstream Vault App re-deposit or refund. Does not restore consumed rate
     * cap — the consumed amount was recorded in the original window and cannot be
     * safely restored in the current window.
     * @param queueId The ID of the queued request to cancel
     */
    function cancelQueuedDraw(uint256 queueId) external;

    /**
     * @notice Redirect an unfulfillable request to a new recipient
     * @dev Only VAULT_CURATOR_ROLE can call. Request must be Unfulfillable.
     * Transfers funds to newRecipient and calls queuedDrawProcessed callback with Fulfilled status.
     * @param queueId The ID of the unfulfillable request
     * @param newRecipient The new recipient address (must be non-zero)
     */
    function redirectUnfulfillable(uint256 queueId, address newRecipient) external;

    /**
     * @notice Fulfill the next pending request in the queue for an asset
     * @dev Permissionless. Processes exactly one request (success, unfulfillable, or insufficient liquidity).
     * Returns no-op result if queue is empty. Uses idle + liquid adapters only.
     * @param asset The asset queue to process
     * @return result FulfillResult with amounts and counts
     */
    function fulfillNext(address asset) external returns (FulfillResult memory result);

    /**
     * @notice Batch fulfill pending requests in the queue
     * @dev Permissionless. Stops at first insufficient liquidity or after maxCount requests.
     * Skips and cleans up cancelled entries. Uses idle + liquid adapters only.
     * @param asset The asset queue to process
     * @param maxCount Maximum number of requests to fulfill
     * @return result FulfillResult with amounts and counts
     */
    function batchFulfill(address asset, uint256 maxCount) external returns (FulfillResult memory result);

    /**
     * @notice Allocate idle funds to an Adapter for investment
     * @dev Only Allocator role can call. Must check allocation caps.
     * Transfers ERC20 to Adapter, then calls allocate on Adapter.
     * @param adapter Address of the Adapter
     * @param asset Address of the asset to allocate
     * @param amount Amount to allocate
     * @param data Additional data for the Adapter
     */
    function allocate(address adapter, address asset, uint256 amount, bytes calldata data) external;

    /**
     * @notice Deallocate funds from an Adapter back to the Vault
     * @dev Only Allocator role can call. Calls deallocate on Adapter,
     * then transfers ERC20 from Adapter to Vault.
     * @param adapter Address of the Adapter
     * @param asset Address of the asset to deallocate
     * @param amount Amount to deallocate
     * @param data Additional data for the Adapter
     */
    function deallocate(address adapter, address asset, uint256 amount, bytes calldata data) external;

    /**
     * @notice Prepare deallocation for illiquid investments with cooldown periods
     * @dev Only Allocator role can call. Calls prepareDeallocation on Adapter.
     * Must wait for cooldown before calling deallocate.
     * @param adapter Address of the Adapter
     * @param asset Address of the asset
     * @param amount Amount to prepare for deallocation
     * @param data Additional data for the Adapter
     */
    function prepareDeallocation(address adapter, address asset, uint256 amount, bytes calldata data) external;

    /**
     * @notice Emergency-withdraw `amount` of `asset` to `recipient`, bypassing app draw caps
     * and the FIFO draw queue
     * @dev Only `VAULT_ADMIN_ROLE`. Trusted backdoor for stranded-fund recovery — e.g. a
     * cross-chain deposit whose hub-side handler permanently reverts, leaving underlying in
     * the Vault with no app-side exit. If idle balance is short of `amount`, the shortfall is
     * pulled from liquid adapters via the best-effort deallocation walk (CLOV-676: a
     * paused/reverting adapter is skipped, so the walk may under-pull); if the full `amount`
     * still cannot be gathered, the transfer reverts — no partial withdrawal. Funds held by
     * non-liquid adapters are not reachable; deallocate them to idle first.
     *
     * WARNING: withdrawing underlying that still backs minted uTokens undercollateralizes the
     * protocol. Intended use is recovering surplus / never-minted deposits only.
     * @param asset Address of the asset to withdraw
     * @param amount Exact amount to withdraw (reverts if unavailable)
     * @param recipient Address receiving the funds (must be non-zero)
     */
    function emergencyWithdraw(address asset, uint256 amount, address recipient) external;

    /**
     * @notice Get the queue length for an asset
     * @dev Includes cancelled items due to lazy removal
     * @param asset The asset to query
     * @return length The number of items in the queue
     */
    function getQueueLength(address asset) external view returns (uint256 length);

    /**
     * @notice Get a queued request by ID
     * @dev Returns empty struct (caller == address(0)) if request doesn't exist
     * @param queueId The queue ID to query
     * @return request The queued request details
     */
    function getQueuedRequest(uint256 queueId) external view returns (QueuedRequest memory request);

    /**
     * @notice Get the idle ERC20 balance of an asset in the Vault
     * @dev Returns only idle funds, not invested amounts in adapters
     * @param asset Address of the asset
     * @return Idle balance of the asset
     */
    function idleBalance(address asset) external view returns (uint256);

    /**
     * @notice Get the liquid ERC20 balance of an asset in the Vault
     * @dev Returns idle funds + invested amounts in liquid adapters
     * @param asset Address of the asset
     * @return Liquid balance of the asset
     */
    function liquidBalance(address asset) external view returns (uint256);

    /**
     * @notice Get the total balance of an asset across all Adapters
     * @dev Returns deposited balance + gains or losses, minimum is 0
     * If an adapter reverts on realAssets(), returns 0 for that adapter and continues
     * @param asset Address of the asset
     * @return Total balance across all adapters
     */
    function adaptersBalance(address asset) external view returns (uint256);

    /**
     * @notice Get the configuration for a Vault App
     * @param app Address of the Vault App
     * @return AppConfig struct containing the app's configuration
     */
    function vaultApps(address app) external view returns (AppConfig memory);

    /**
     * @notice Get the caps for a Vault App and asset
     * @param app Address of the Vault App
     * @param asset Address of the asset
     * @return AppCaps struct containing draw and supply caps
     */
    function appCaps(address app, address asset) external view returns (AppCaps memory);

    /**
     * @notice Get the caps for an Adapter and asset
     * @param adapter Address of the Adapter
     * @param asset Address of the asset
     * @return AdapterCaps struct containing the allocation cap
     */
    function adapterCaps(address adapter, address asset) external view returns (AdapterCaps memory);

    /// @notice Get the per-asset stock cap (holdings ceiling) for `asset`.
    /// @param asset The underlying asset.
    /// @return The configured holdings ceiling (0 = blocked, type(uint256).max = unlimited).
    function vaultStockCap(address asset) external view returns (uint256);

    /**
     * @notice Get all adapters configured for an asset with their current state
     * @dev Returns adapter info including principal (if available), realAssets, caps, and status
     * @param asset Address of the asset
     * @return Array of AdapterInfo structs
     */
    function getAdapters(address asset) external view returns (AdapterInfo[] memory);
}

src/protocol/vault/interfaces/IVaultApp.sol

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

import {QueuedRequestStatus} from "../Types.sol";
import {IVault} from "./IVault.sol";

/**
 * @title IVaultApp
 * @notice Base interface for Vault Apps that interact with the Vault
 * @dev Vault Apps are user-facing contracts that can supply/draw funds from the Vault
 * Examples: Bridge, Lending Protocol, DEX, Savings Vault
 */
interface IVaultApp {
    /**
     * @notice Callback when a queued draw request is processed (fulfilled or unfulfillable)
     * @dev Called by Vault after processing the request. MUST verify msg.sender == address(VAULT).
     * For Fulfilled: called after transferring funds to recipient.
     * For Unfulfillable: called after marking request as unfulfillable (funds remain in Vault).
     * Revert will cause the entire transaction to revert.
     * @param queueId The ID of the processed request
     * @param recipient The actual recipient (may differ from original if redirected)
     * @param status The outcome: Fulfilled or Unfulfillable
     */
    function queuedDrawProcessed(uint256 queueId, address recipient, QueuedRequestStatus status) external;

    /**
     * @notice Get the Vault this app is associated with
     * @return The Vault contract
     */
    function vault() external view returns (IVault);

    /**
     * @notice Get the supported assets for this Vault App
     * @return Array of supported asset addresses
     */
    function supportedAssets() external view returns (address[] memory);

    /**
     * @notice Check if the Vault App is currently active
     * @return True if active, false otherwise
     */
    function isActive() external view returns (bool);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=src/dependencies/openzeppelin/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@layerzerolabs/lz-evm-oapp-v2/=src/dependencies/@layerzerolabs/lz-evm-oapp-v2/",
    "@layerzerolabs/lz-evm-protocol-v2/contracts/=src/dependencies/@layerzerolabs/lz-evm-protocol-v2/",
    "@layerzerolabs/oft-evm-upgradeable/=lib/devtools/packages/oft-evm-upgradeable/",
    "@layerzerolabs/oapp-evm-upgradeable/=lib/devtools/packages/oapp-evm-upgradeable/",
    "@layerzerolabs/oapp-evm/=lib/devtools/packages/oapp-evm/",
    "@layerzerolabs/oft-evm/=lib/devtools/packages/oft-evm/",
    "@layerzerolabs/test-devtools-evm-foundry/=lib/devtools/packages/test-devtools-evm-foundry/",
    "@axelar-network/axelar-gmp-sdk-solidity/=src/dependencies/@axelar-network/axelar-gmp-sdk-solidity/",
    "@chainlink/contracts-ccip/=src/dependencies/@chainlink/contracts-ccip/",
    "@wormhole-foundation/wormhole-solidity-sdk/=src/dependencies/@wormhole-foundation/wormhole-solidity-sdk/",
    "wormhole-sdk/=lib/wormhole-solidity-sdk/src/",
    "@bundler3/=lib/bundler3/src/",
    "@morpho-blue/=lib/bundler3/lib/morpho-blue/src/",
    "@hyperlane/=lib/hyperlane-monorepo/solidity/",
    "morpho-vault-v2/=lib/morpho-vault-v2/",
    "morpho-vault-v2-adapter-registries/=lib/morpho-vault-v2-adapter-registries/",
    "evk/=lib/evk-periphery/lib/euler-vault-kit/src/",
    "evc/=lib/evk-periphery/lib/ethereum-vault-connector/src/",
    "ethereum-vault-connector/=lib/evk-periphery/lib/ethereum-vault-connector/src/",
    "euler-price-oracle/=lib/evk-periphery/lib/euler-price-oracle/src/",
    "reward-streams/=lib/evk-periphery/lib/reward-streams/src/",
    "evk-periphery/=lib/evk-periphery/src/",
    "permit2/=lib/evk-periphery/lib/euler-vault-kit/lib/permit2/",
    "lib/evk-periphery/:openzeppelin-contracts/=lib/evk-periphery/lib/openzeppelin-contracts/contracts/",
    "lib/evk-periphery/:openzeppelin-contracts-upgradeable/=lib/evk-periphery/lib/openzeppelin-contracts-upgradeable/contracts/",
    "lib/evk-periphery/:@openzeppelin/contracts/=lib/evk-periphery/lib/openzeppelin-contracts/contracts/",
    "lib/evk-periphery/lib/euler-price-oracle/:@openzeppelin/contracts/=lib/evk-periphery/lib/euler-price-oracle/lib/openzeppelin-contracts/contracts/",
    "@ensdomains/=lib/evk-periphery/lib/euler-swap/lib/v4-periphery/lib/v4-core/node_modules/@ensdomains/",
    "@layerzerolabs/lz-evm-messagelib-v2/=lib/evk-periphery/lib/layerzero-v2/packages/layerzero-v2/evm/messagelib/",
    "@pendle/core-v2/=lib/evk-periphery/lib/euler-price-oracle/lib/pendle-core-v2-public/contracts/",
    "@pyth/=lib/evk-periphery/lib/euler-price-oracle/lib/pyth-sdk-solidity/",
    "@redstone/evm-connector/=lib/evk-periphery/lib/euler-price-oracle/lib/redstone-oracles-monorepo/packages/evm-connector/contracts/",
    "@solady/=lib/evk-periphery/lib/euler-price-oracle/lib/solady/src/",
    "@uniswap/v3-core/=lib/evk-periphery/lib/euler-price-oracle/lib/v3-core/",
    "@uniswap/v3-periphery/=lib/evk-periphery/lib/euler-price-oracle/lib/v3-periphery/",
    "@uniswap/v4-core/=lib/evk-periphery/lib/euler-swap/lib/v4-periphery/lib/v4-core/",
    "IERC20/=lib/wormhole-solidity-sdk/src/interfaces/token/",
    "SafeERC20/=lib/wormhole-solidity-sdk/src/libraries/",
    "bundler3/=lib/bundler3/",
    "devtools/=lib/devtools/packages/toolbox-foundry/src/",
    "ds-test/=lib/wormhole-solidity-sdk/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "euler-earn/=lib/evk-periphery/lib/euler-earn/",
    "euler-price-oracle-test/=lib/evk-periphery/lib/euler-price-oracle/test/",
    "euler-swap/=lib/evk-periphery/lib/euler-swap/",
    "euler-vault-kit/=lib/evk-periphery/lib/euler-vault-kit/",
    "evk-test/=lib/evk-periphery/lib/euler-vault-kit/test/",
    "fee-flow/=lib/evk-periphery/lib/fee-flow/",
    "forge-gas-snapshot/=lib/bundler3/lib/permit2/lib/forge-gas-snapshot/src/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/evk-periphery/lib/euler-swap/lib/v4-periphery/lib/v4-core/node_modules/hardhat/",
    "hyperlane-monorepo/=lib/hyperlane-monorepo/",
    "layerzero-devtools/=lib/evk-periphery/lib/layerzero-devtools/packages/toolbox-foundry/src/",
    "layerzero-v2/=lib/evk-periphery/lib/",
    "layerzero/oft-evm-upgradeable/=lib/evk-periphery/lib/layerzero-devtools/packages/oft-evm-upgradeable/contracts/",
    "layerzero/oft-evm/=lib/evk-periphery/lib/layerzero-devtools/packages/oft-evm/contracts/",
    "metamorpho-v1.1/=lib/morpho-vault-v2/lib/metamorpho-v1.1/",
    "metamorpho/=lib/morpho-vault-v2/lib/metamorpho/",
    "morpho-blue-irm/=lib/morpho-vault-v2/lib/morpho-blue-irm/",
    "morpho-blue-oracles/=lib/morpho-blue-oracles/src/",
    "morpho-blue/=lib/morpho-vault-v2/lib/morpho-blue/",
    "murky/=lib/morpho-vault-v2-adapter-registries/lib/metamorpho/lib/universal-rewards-distributor/lib/murky/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
    "openzeppelin/=lib/evk-periphery/lib/ethereum-vault-connector/lib/openzeppelin-contracts/contracts/",
    "pendle-core-v2-public/=lib/evk-periphery/lib/euler-price-oracle/lib/pendle-core-v2-public/contracts/",
    "pyth-sdk-solidity/=lib/evk-periphery/lib/euler-price-oracle/lib/pyth-sdk-solidity/",
    "redstone-oracles-monorepo/=lib/evk-periphery/lib/euler-price-oracle/lib/",
    "solady/=lib/evk-periphery/lib/euler-price-oracle/lib/solady/src/",
    "solidity-bytes-utils/=lib/evk-periphery/lib/solidity-bytes-utils/",
    "solmate/=lib/bundler3/lib/permit2/lib/solmate/",
    "universal-rewards-distributor/=lib/morpho-vault-v2-adapter-registries/lib/metamorpho/lib/universal-rewards-distributor/src/",
    "v3-core/=lib/evk-periphery/lib/euler-price-oracle/lib/v3-core/contracts/",
    "v3-periphery/=lib/evk-periphery/lib/euler-price-oracle/lib/v3-periphery/contracts/",
    "v4-core/=lib/evk-periphery/lib/euler-swap/lib/v4-periphery/lib/v4-core/src/",
    "v4-periphery/=lib/evk-periphery/lib/euler-swap/lib/v4-periphery/",
    "vault-v2/=lib/morpho-vault-v2-adapter-registries/lib/vault-v2/",
    "wormhole-solidity-sdk/=lib/wormhole-solidity-sdk/src/",
    "lib/euler-earn:@openzeppelin-upgradeable/=lib/evk-periphery/lib/euler-earn/lib/openzeppelin-contracts-upgradeable/contracts/",
    "lib/euler-earn:@openzeppelin/=lib/evk-periphery/lib/euler-earn/lib/openzeppelin-contracts/",
    "lib/euler-earn:ethereum-vault-connector/=lib/evk-periphery/lib/euler-earn/lib/ethereum-vault-connector/src/",
    "lib/euler-price-oracle:@openzeppelin/contracts/=lib/evk-periphery/lib/euler-price-oracle/lib/openzeppelin-contracts/contracts/",
    "lib/euler-swap:solmate/=lib/evk-periphery/lib/euler-swap/lib/v4-periphery/lib/v4-core/lib/solmate/src/",
    "lib/fee-flow/src:solmate/=lib/evk-periphery/lib/fee-flow/lib/solmate/src/",
    "lib/fee-flow/tokens:solmate/=lib/evk-periphery/lib/fee-flow/lib/solmate/tokens/",
    "lib/fee-flow/utils:solmate/=lib/evk-periphery/lib/fee-flow/lib/solmate/utils/",
    "lib/layerzero-devtools/packages/oapp-evm-upgradeable/contracts:@openzeppelin/contracts-upgradeable/=lib/evk-periphery/lib/openzeppelin-contracts-upgradeable/contracts/",
    "lib/layerzero-devtools/packages/oft-evm-upgradeable/contracts:@openzeppelin/contracts-upgradeable/=lib/evk-periphery/lib/openzeppelin-contracts-upgradeable/contracts/",
    "lib/layerzero-devtools/packages/oft-evm/contracts:@openzeppelin/contracts-upgradeable/=lib/evk-periphery/lib/openzeppelin-contracts/contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.