Skip to content
Verified contractExactBUSL-1.1

BridgeVaultAppInstance

Address0xb28ecae1c5b4eae07436aa921a99595f7c1cfa18
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,883
Creation transaction
0x58d0e40a69…a3689dde66

32 files

src/protocol/bridge/BridgeVaultAppInstance.sol

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

import {BridgeVaultApp} from "./BridgeVaultApp.sol";
import {IIncomeCollector} from "../incomeCollector/interfaces/IIncomeCollector.sol";
import {IAttestationService} from "../attestation/interfaces/IAttestationService.sol";
import {ZeroAddress} from "../mba/interfaces/MBAErrors.sol";

/**
 * @title BridgeVaultAppInstance
 * @author Clovis Protocol
 * @notice Concrete implementation of BridgeVaultApp for deployment
 * @dev Allows direct instantiation for testing and deployment
 */
/// @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 BridgeVaultAppInstance is BridgeVaultApp {
    uint256 public constant BRIDGE_REVISION = 2;

    constructor(address vault_, address crossMessageController_, address accessControl_)
        BridgeVaultApp(vault_, crossMessageController_, accessControl_)
    {}

    /**
     * @notice Initialize the BridgeVaultApp
     * @param incomeCollector_ IncomeCollector contract address
     * @param attestationService_ AttestationService contract address
     */
    function initialize(address incomeCollector_, address attestationService_) public virtual override initializer {
        if (incomeCollector_ == address(0)) revert ZeroAddress();
        if (attestationService_ == address(0)) revert ZeroAddress();

        _incomeCollector = IIncomeCollector(incomeCollector_);
        _attestationService = IAttestationService(attestationService_);
    }

    /**
     * @notice Returns the revision number
     * @return Revision number
     */
    function getRevision() internal pure virtual override returns (uint256) {
        return BRIDGE_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/extensions/IERC20Metadata.sol

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

pragma solidity >=0.6.2;

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

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

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

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

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/dependencies/openzeppelin/utils/structs/EnumerableSet.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 */
library EnumerableSet {
    struct Set {
        bytes32[] _values;
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        uint256 position = set._positions[value];
        if (position != 0) {
            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];
                set._values[valueIndex] = lastValue;
                set._positions[lastValue] = position;
            }

            set._values.pop();
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        return store;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }
}

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/bridge/BridgeVaultApp.sol

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

import {IBridgeVaultApp} from "./interfaces/IBridgeVaultApp.sol";
import {IIncomeCollector, RevenueSource} from "../incomeCollector/interfaces/IIncomeCollector.sol";
import {IVault} from "../vault/interfaces/IVault.sol";
import {IVaultApp} from "../vault/interfaces/IVaultApp.sol";
import {MessageHandlerUpgradeable} from "../mba/handlers/MessageHandlerUpgradeable.sol";
import {IMessageHandler} from "../mba/interfaces/IMessageHandler.sol";
import {MessageOrigin, MessageType} from "../mba/libraries/MessageLib.sol";
import {ZeroAddress} from "../mba/interfaces/MBAErrors.sol";
import {AddressConversion} from "../mba/libraries/AddressConversion.sol";
import {ReentrancyGuardTransient} from "../../dependencies/openzeppelin/utils/ReentrancyGuardTransient.sol";
import {IERC20} from "../../dependencies/openzeppelin/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../../dependencies/openzeppelin/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "../../dependencies/openzeppelin/token/ERC20/utils/SafeERC20.sol";
import {EnumerableSet} from "../../dependencies/openzeppelin/utils/structs/EnumerableSet.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {IAttestationService} from "../attestation/interfaces/IAttestationService.sol";
import {Attestation} from "../attestation/AttestationTypes.sol";
import {QueuedRequestStatus, DrawResult, DrawStatus} from "../vault/Types.sol";
import {Pausable} from "../../dependencies/openzeppelin/utils/Pausable.sol";
import {PauseRoles} from "../access/PauseRoles.sol";

error UnsupportedAsset(address asset);
error AssetAlreadySupported(address asset);
error AssetNotSupported(address asset);
error AssetHasInboundMappings(address asset);
error InsufficientLiquidity();
error BridgeRequestNotFound(uint256 bridgeId);
error BridgeRequestNotCancellable(uint256 bridgeId);
error FeeTooHigh(uint256 fee);
error InvalidRecipient();
error InvalidMapping();
error IncomeCollectorNotSet();
error NotVault();
error NotAuthorized();
error InvalidSharedDecimals(uint8 sharedDecimals, uint8 localDecimals);
error SharedDecimalsAlreadySet(address asset, uint8 current);
error SharedDecimalsNotSet(address asset);
error SharedDecimalsImmutable(address asset, uint8 prior, uint8 requested);
error AmountTooSmall();
error CannotRescueProtectedFees(address token, uint256 protectedAmount, uint256 balance, uint256 requested);

/**
 * @title BridgeVaultApp
 * @author Clovis Protocol
 * @notice Pool-based bridge that uses Vault liquidity for cross-chain asset transfers
 * @dev Abstract contract implementing core bridge functionality
 * @dev Extends MessageHandlerUpgradeable for standardized cross-chain message handling with EIP-165 support
 */
abstract contract BridgeVaultApp is
    IBridgeVaultApp,
    IVaultApp,
    MessageHandlerUpgradeable,
    ReentrancyGuardTransient,
    Pausable
{
    using AddressConversion for address;

    using AddressConversion for bytes32;

    using SafeERC20 for IERC20;

    using EnumerableSet for EnumerableSet.AddressSet;

    using EnumerableSet for EnumerableSet.Bytes32Set;

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

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

    uint256 public constant MAX_FEE = 10000; // 100% in basis points

    IVault public immutable VAULT;

    IIncomeCollector internal _incomeCollector;

    IAttestationService internal _attestationService;

    mapping(address => uint256) internal _bridgeFees; // asset => fee in basis points
    mapping(address => uint256) internal _collectedBridgeFees; // asset => collected bridge-fee amount (BRIDGE_FEES)

    EnumerableSet.AddressSet internal _supportedAssets;

    // Mapping: sourceChainId => sourceAsset (bytes32) => localAsset
    // Uses bytes32 for sourceAsset to support both EVM addresses (left-padded) and non-EVM addresses (e.g., Solana Mints)
    mapping(uint256 => mapping(bytes32 => address)) internal _assetMappings;

    mapping(uint256 => BridgeRequest) internal _bridgeRequests;

    uint256 internal _incomingBridgeId; // Counter for bridge IDs on destination chain (incoming requests)

    // Reverse lookup: vaultQueueId => bridgeId (for callback)
    mapping(uint256 => uint256) internal _vaultQueueIdToBridgeId;

    uint256 internal _outgoingBridgeId; // Counter for bridge IDs on source chain (outgoing requests)

    /// @dev Local asset address => shared decimals for cross-chain encoding.
    ///      Append-once: written on the first `addSupportedAsset` and never cleared.
    ///      `removeSupportedAsset` deactivates the asset by removing it from
    ///      `_supportedAssets` but leaves this entry intact so any future re-add must
    ///      reuse the same value (`SharedDecimalsImmutable` otherwise). This prevents
    ///      the remove-then-re-add path from silently reinterpreting in-flight messages
    ///      encoded under the original value.
    mapping(address => uint8) internal _sharedDecimals;

    /// @dev Reverse index from a local asset to the set of (sourceChainId, sourceAsset)
    ///      mapping keys that resolve to it. Keys are encoded as
    ///      `keccak256(abi.encode(sourceChainId, sourceAsset))`. Used by
    ///      `removeSupportedAsset` to refuse removing an asset that still has inbound
    ///      mappings pointing at it.
    mapping(address => EnumerableSet.Bytes32Set) internal _assetMappingsByLocal;

    /// @dev Preset-fee portion of collected bridge fees, ships as RevenueSource.OTHERS.
    ///      Appended at the trailing gap (slot 115) when splitting the legacy single
    ///      `_collectedBridgeFees` bucket (CLOV-678); `__gap` shrunk 37→36 to keep the layout
    ///      append-only. Pre-upgrade commingled fees remain in `_collectedBridgeFees`.
    mapping(address => uint256) internal _collectedPresetFees;

    uint256[36] private __gap;

    modifier onlyVault() {
        if (msg.sender != address(VAULT)) revert NotVault();
        _;
    }

    constructor(address vault_, address crossMessageController_, address accessControl_)
        MessageHandlerUpgradeable(crossMessageController_, accessControl_)
    {
        if (vault_ == address(0)) revert ZeroAddress();
        VAULT = IVault(vault_);
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function bridge(
        Attestation calldata attestation,
        address asset,
        uint256 amount,
        uint256 destChainId,
        bytes32 recipient,
        bytes32 presetId
    ) external payable override nonReentrant whenNotPaused returns (bytes32 messageId) {
        return _bridge(attestation, asset, amount, destChainId, recipient, presetId, msg.sender);
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function bridge(
        Attestation calldata attestation,
        address asset,
        uint256 amount,
        uint256 destChainId,
        bytes32 recipient,
        bytes32 presetId,
        address cancelAddress
    ) external payable override nonReentrant whenNotPaused returns (bytes32 messageId) {
        return _bridge(attestation, asset, amount, destChainId, recipient, presetId, cancelAddress);
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function bridge(
        Attestation calldata attestation,
        address asset,
        uint256 amount,
        uint256 destChainId,
        bytes32 recipient
    ) external payable override nonReentrant whenNotPaused returns (bytes32 messageId) {
        return _bridge(attestation, asset, amount, destChainId, recipient, bytes32(0), msg.sender);
    }

    /**
     * @inheritdoc IVaultApp
     */
    function queuedDrawProcessed(uint256 queueId, address recipient, QueuedRequestStatus status) external onlyVault {
        uint256 bridgeId = _vaultQueueIdToBridgeId[queueId];
        BridgeRequest storage request = _bridgeRequests[bridgeId];

        if (status == QueuedRequestStatus.Fulfilled) {
            request.status = BridgeRequestStatus.Fulfilled;
            emit BridgeRequestFulfilled(
                bridgeId, recipient, request.asset, request.amount, request.sourceChainId, request.bridgeId
            );
        } else if (status == QueuedRequestStatus.Unfulfillable) {
            request.status = BridgeRequestStatus.Unfulfillable;
            emit BridgeRequestUnfulfillable(bridgeId, request.sourceChainId, request.bridgeId);
        }
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function cancelBridgeRequest(Attestation calldata attestation, uint256 localBridgeId)
        external
        payable
        override
        nonReentrant
        returns (uint256 refundBridgeId)
    {
        _attestationService.verify(attestation, msg.sender, address(this), msg.value, msg.data);

        BridgeRequest storage request = _bridgeRequests[localBridgeId];

        if (request.amount == 0) revert BridgeRequestNotFound(localBridgeId);

        _validateCancellation(request, localBridgeId);

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

        // Set status to Cancelled
        request.status = BridgeRequestStatus.Cancelled;

        // Refund the original sender on the source chain. `request.origin.sourceSender` is
        // the source-side BridgeVaultApp contract address (used by MessageHandler for peer
        // validation) and must not be used as a refund target. The refund's `sender` is the
        // canceller (msg.sender) — recorded as the new destination's `originalSender` so
        // that, if this refund itself stalls on the source chain and gets cancelled (e.g.,
        // the original user is now an unreachable contract), the refund-of-refund lands
        // back here at the canceller, who has chain-context to retry or redirect.
        bytes32 refundRecipient = request.originalSender;
        (refundBridgeId,) = _sendBridgeMessage(
            request.sourceChainId,
            request.asset,
            request.amount,
            refundRecipient,
            msg.sender,
            0, // no fee for refunds
            bytes32(0) // default preset
        );

        emit BridgeRequestCancelled(localBridgeId, refundRecipient, request.sourceChainId, request.bridgeId);

        return refundBridgeId;
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function dropBridgeRequest(uint256 bridgeId) external override onlyRole(BRIDGE_ADMIN_ROLE) {
        BridgeRequest storage request = _bridgeRequests[bridgeId];

        if (request.amount == 0) revert BridgeRequestNotFound(bridgeId);

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

        // Mark as Cancelled (logical delete without refund)
        request.status = BridgeRequestStatus.Cancelled;

        emit BridgeRequestCancelled(bridgeId, bytes32(0), request.sourceChainId, request.bridgeId);
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function setBridgeFee(address asset, uint256 feePercent) external override onlyRole(BRIDGE_ADMIN_ROLE) {
        if (feePercent > MAX_FEE) revert FeeTooHigh(feePercent);

        _bridgeFees[asset] = feePercent;

        emit BridgeFeeSet(asset, feePercent);
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function addSupportedAsset(address asset, uint8 sharedDecimals_) external override onlyRole(BRIDGE_ADMIN_ROLE) {
        if (asset == address(0)) revert ZeroAddress();
        if (!_supportedAssets.add(asset)) revert AssetAlreadySupported(asset);

        // Reject re-adds that try to change the shared-decimals — silent reinterpretation
        // of in-flight messages would be catastrophic. `_sharedDecimals` is append-once
        // (see storage doc): a non-zero prior entry means this asset was previously
        // listed and its decimals are now locked.
        uint8 prior = _sharedDecimals[asset];
        if (prior != 0 && prior != sharedDecimals_) {
            revert SharedDecimalsImmutable(asset, prior, sharedDecimals_);
        }

        _validateSharedDecimals(asset, sharedDecimals_);
        _sharedDecimals[asset] = sharedDecimals_;

        IERC20Metadata token = IERC20Metadata(asset);
        emit AssetAdded(asset, token.symbol(), token.decimals());
        emit SharedDecimalsSet(asset, sharedDecimals_);
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function removeSupportedAsset(address asset) external override onlyRole(BRIDGE_ADMIN_ROLE) {
        // Refuse to remove an asset that still has inbound mappings pointing at it.
        // Admin must call removeAssetMapping for every such (sourceChainId, sourceAsset)
        // pair first. Combined with the CLOV-471 `_supportedAssets.contains` check in
        // `_resolveLocalAsset`, this guarantees no inbound message can resolve to a
        // removed asset and hit `_toLocalDecimals`.
        if (_assetMappingsByLocal[asset].length() > 0) revert AssetHasInboundMappings(asset);
        if (!_supportedAssets.remove(asset)) revert AssetNotSupported(asset);

        // Intentionally NOT deleting _sharedDecimals — see storage doc. The value must
        // persist so any future re-add cannot select a different shared-decimals.

        emit AssetRemoved(asset);
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function setAssetMapping(uint256 sourceChainId, bytes32 sourceAsset, address localAsset)
        external
        override
        onlyRole(BRIDGE_ADMIN_ROLE)
    {
        _setAssetMapping(sourceChainId, sourceAsset, localAsset);
    }

    /**
     * @notice Set asset mapping using EVM address for source asset
     * @dev Convenience function for EVM-to-EVM mappings
     * @param sourceChainId Source chain ID
     * @param sourceAsset Source asset EVM address
     * @param localAsset Local asset address
     */
    function setAssetMappingAddress(uint256 sourceChainId, address sourceAsset, address localAsset)
        external
        onlyRole(BRIDGE_ADMIN_ROLE)
    {
        if (sourceAsset == address(0)) revert ZeroAddress();
        _setAssetMapping(sourceChainId, sourceAsset.addressToBytes32(), localAsset);
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function removeAssetMapping(uint256 sourceChainId, bytes32 sourceAsset)
        external
        override
        onlyRole(BRIDGE_ADMIN_ROLE)
    {
        if (sourceAsset == bytes32(0)) revert ZeroAddress();
        address localAsset = _assetMappings[sourceChainId][sourceAsset];
        if (localAsset == address(0)) revert InvalidMapping();

        delete _assetMappings[sourceChainId][sourceAsset];
        _assetMappingsByLocal[localAsset].remove(_mappingKey(sourceChainId, sourceAsset));

        emit AssetMappingRemoved(sourceChainId, sourceAsset, localAsset);
    }

    /**
     * @notice Remove an asset mapping using EVM address for source asset
     * @dev Convenience function for EVM-to-EVM mappings
     * @param sourceChainId Source chain ID
     * @param sourceAsset Source asset EVM address
     */
    function removeAssetMappingAddress(uint256 sourceChainId, address sourceAsset)
        external
        onlyRole(BRIDGE_ADMIN_ROLE)
    {
        if (sourceAsset == address(0)) revert ZeroAddress();
        bytes32 sourceAssetBytes32 = sourceAsset.addressToBytes32();
        address localAsset = _assetMappings[sourceChainId][sourceAssetBytes32];
        if (localAsset == address(0)) revert InvalidMapping();

        delete _assetMappings[sourceChainId][sourceAssetBytes32];
        _assetMappingsByLocal[localAsset].remove(_mappingKey(sourceChainId, sourceAssetBytes32));

        emit AssetMappingRemoved(sourceChainId, sourceAssetBytes32, localAsset);
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function setIncomeCollector(address collector) external override onlyRole(BRIDGE_ADMIN_ROLE) {
        if (collector == address(0)) revert ZeroAddress();

        address previousCollector = address(_incomeCollector);
        _incomeCollector = IIncomeCollector(collector);

        emit IncomeCollectorSet(previousCollector, collector);
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function setAttestationService(address attestationService_) external override onlyRole(BRIDGE_ADMIN_ROLE) {
        if (attestationService_ == address(0)) revert ZeroAddress();

        address previousService = address(_attestationService);
        _attestationService = IAttestationService(attestationService_);

        emit AttestationServiceSet(previousService, attestationService_);
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function setSharedDecimals(address asset, uint8 sharedDecimals_) external override onlyRole(BRIDGE_ADMIN_ROLE) {
        if (asset == address(0)) revert ZeroAddress();
        if (!_supportedAssets.contains(asset)) revert AssetNotSupported(asset);
        uint8 current = _sharedDecimals[asset];
        if (current != 0) revert SharedDecimalsAlreadySet(asset, current);

        _validateSharedDecimals(asset, sharedDecimals_);
        _sharedDecimals[asset] = sharedDecimals_;

        emit SharedDecimalsSet(asset, sharedDecimals_);
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function backfillAssetMapping(uint256 sourceChainId, bytes32 sourceAsset)
        external
        override
        onlyRole(BRIDGE_ADMIN_ROLE)
    {
        address localAsset = _assetMappings[sourceChainId][sourceAsset];
        if (localAsset == address(0)) revert InvalidMapping();
        _assetMappingsByLocal[localAsset].add(_mappingKey(sourceChainId, sourceAsset));
    }

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

        uint256 bridgeFees = _collectedBridgeFees[asset];
        uint256 presetFees = _collectedPresetFees[asset];
        if (bridgeFees == 0 && presetFees == 0) return;

        // Reset accumulated fees before external calls (CEI).
        _collectedBridgeFees[asset] = 0;
        _collectedPresetFees[asset] = 0;

        // Bridge portion → BRIDGE_FEES; preset portion → OTHERS (relayer/faster-tier
        // risk compensation routed through its own RevenueRouter split). CLOV-678.
        if (bridgeFees > 0) {
            IERC20(asset).forceApprove(address(_incomeCollector), bridgeFees);
            _incomeCollector.collectIncome(asset, bridgeFees, RevenueSource.BRIDGE_FEES);
        }
        if (presetFees > 0) {
            IERC20(asset).forceApprove(address(_incomeCollector), presetFees);
            _incomeCollector.collectIncome(asset, presetFees, RevenueSource.OTHERS);
        }

        emit FeesCollected(asset, bridgeFees + presetFees, address(_incomeCollector));
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function rescueTokens(address token, address recipient, uint256 amount)
        external
        override
        onlyRole(BRIDGE_ADMIN_ROLE)
    {
        if (token == address(0) || recipient == address(0)) revert ZeroAddress();

        uint256 protectedAmount = _collectedBridgeFees[token] + _collectedPresetFees[token];
        uint256 balance = IERC20(token).balanceOf(address(this));
        // `balance < protectedAmount` should not occur if the contract is in a consistent
        // state, but guard against it explicitly so the subtraction below can never wrap
        // and silently approve a sweep.
        if (balance < protectedAmount || balance - protectedAmount < amount) {
            revert CannotRescueProtectedFees(token, protectedAmount, balance, amount);
        }

        IERC20(token).safeTransfer(recipient, amount);

        emit TokensRescued(token, recipient, amount);
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function pauseBridge() external override onlyRole(BRIDGE_GUARDIAN_ROLE) {
        if (paused()) return;
        _pause();
        emit BridgePaused(msg.sender);
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function unpauseBridge() external override onlyRole(PauseRoles.UNPAUSER_ROLE) {
        _unpause();
        emit BridgeUnpaused(msg.sender);
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function estimateBridgeFee(address asset, uint256 amount, uint256 destChainId, bytes32 recipient, bytes32 presetId)
        external
        view
        override
        returns (uint256 totalFee, uint256[] memory adapterFees)
    {
        return _estimateBridgeFee(asset, amount, destChainId, recipient, presetId);
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function estimateBridgeFee(address asset, uint256 amount, uint256 destChainId, bytes32 recipient)
        external
        view
        override
        returns (uint256 totalFee, uint256[] memory adapterFees)
    {
        return _estimateBridgeFee(asset, amount, destChainId, recipient, bytes32(0));
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function getBridgeRequest(uint256 bridgeId) external view override returns (BridgeRequest memory) {
        return _bridgeRequests[bridgeId];
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function getBridgeFee(address asset) external view override returns (uint256) {
        return _bridgeFees[asset];
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function getCollectedFees(address asset) external view override returns (uint256) {
        return _collectedBridgeFees[asset] + _collectedPresetFees[asset];
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function isSupportedAsset(address asset) external view override returns (bool) {
        return _supportedAssets.contains(asset);
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function getAssetMapping(uint256 sourceChainId, bytes32 sourceAsset) external view override returns (address) {
        return _assetMappings[sourceChainId][sourceAsset];
    }

    /**
     * @notice Get asset mapping using EVM address for source asset
     * @dev Convenience function for EVM-to-EVM lookups
     * @param sourceChainId Source chain ID
     * @param sourceAsset Source asset EVM address
     * @return Local asset address
     */
    function getAssetMappingAddress(uint256 sourceChainId, address sourceAsset) external view returns (address) {
        return _assetMappings[sourceChainId][sourceAsset.addressToBytes32()];
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function vault() external view override(IBridgeVaultApp, IVaultApp) returns (IVault) {
        return VAULT;
    }

    /**
     * @inheritdoc IVaultApp
     */
    function supportedAssets() external view override returns (address[] memory) {
        return _supportedAssets.values();
    }

    /**
     * @inheritdoc IVaultApp
     */
    function isActive() external view override returns (bool) {
        return !paused();
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function incomeCollector() external view override returns (IIncomeCollector) {
        return _incomeCollector;
    }

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

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function isPaused() external view override returns (bool) {
        return paused();
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function getSharedDecimals(address asset) external view override returns (uint8) {
        return _sharedDecimals[asset];
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function getAvailableLiquidity(uint256 sourceChainId, bytes32 sourceAsset)
        external
        view
        override
        returns (uint256)
    {
        address localAsset = _assetMappings[sourceChainId][sourceAsset];
        if (localAsset == address(0)) {
            return 0;
        }
        return VAULT.liquidBalance(localAsset);
    }

    /**
     * @inheritdoc IBridgeVaultApp
     */
    function estimateCancelBridgeRequestFee(uint256 bridgeId)
        external
        view
        override
        returns (uint256 totalFee, uint256[] memory adapterFees)
    {
        BridgeRequest storage request = _bridgeRequests[bridgeId];
        if (request.amount == 0) revert BridgeRequestNotFound(bridgeId);

        // Build the same refund payload that cancelBridgeRequest would send. The payload
        // is encoded with `msg.sender` as the canceller; the result is for fee estimation
        // only and the encoding shape matches what cancelBridgeRequest dispatches.
        bytes32 refundRecipient = request.originalSender;
        bytes32 localAssetBytes32 = request.asset.addressToBytes32();
        uint256 sharedRefundAmount = _toSharedDecimals(request.asset, request.amount);
        bytes memory refundPayload = abi.encode(
            refundRecipient, localAssetBytes32, sharedRefundAmount, uint256(0), msg.sender.addressToBytes32()
        );

        return CROSS_MESSAGE_CONTROLLER.estimateFees(request.sourceChainId, refundPayload, MessageType.BRIDGE);
    }

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

    function _bridge(
        Attestation calldata attestation,
        address asset,
        uint256 amount,
        uint256 destChainId,
        bytes32 recipient,
        bytes32 presetId,
        address cancelAddress
    ) internal returns (bytes32 messageId) {
        _attestationService.verify(attestation, msg.sender, address(this), msg.value, msg.data);

        if (!_supportedAssets.contains(asset)) revert UnsupportedAsset(asset);
        if (recipient == bytes32(0)) revert InvalidRecipient();
        if (cancelAddress == address(0)) revert ZeroAddress();

        uint256 actualAmount = _doTransferIn(asset, msg.sender, amount);

        uint256 bridgeFeeBps = _bridgeFees[asset];
        uint256 presetFeeBps = _getPresetFeeBps(destChainId, presetId);
        if (bridgeFeeBps + presetFeeBps >= MAX_FEE) revert FeeTooHigh(bridgeFeeBps + presetFeeBps);

        uint256 bridgeFee = (actualAmount * bridgeFeeBps) / 10000;
        uint256 presetFee = (actualAmount * presetFeeBps) / 10000;
        uint256 feeAmount = bridgeFee + presetFee; // still needed for netAmount + the bridge message
        uint256 netAmount = actualAmount - feeAmount;

        _collectedBridgeFees[asset] += bridgeFee;
        _collectedPresetFees[asset] += presetFee;

        IERC20(asset).forceApprove(address(VAULT), netAmount);
        VAULT.supply(asset, netAmount);

        (, messageId) = _sendBridgeMessage(destChainId, asset, netAmount, recipient, cancelAddress, feeAmount, presetId);
    }

    /**
     * @notice Internal message handling logic (overrides MessageHandlerUpgradeable)
     * @param messageId Unique message identifier (generated by MBA system)
     * @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)
        internal
        override
        whenNotPaused
        returns (bool success)
    {
        // Cache source chain ID to avoid stack too deep
        uint256 sourceChainId = origin.sourceChainId;

        // Decode payload (recipient, sourceAsset as bytes32, sharedAmount, bridgeId, originalSender)
        (bytes32 recipient, bytes32 sourceAsset, uint256 sharedAmount, uint256 sourceBridgeId, bytes32 originalSender) =
            abi.decode(payload, (bytes32, bytes32, uint256, uint256, bytes32));

        // Map source asset to local asset and convert shared decimals to local
        address localAsset = _resolveLocalAsset(sourceChainId, sourceAsset);
        uint256 localAmount = _toLocalDecimals(localAsset, sharedAmount);

        // Create bridge request with Pending status and store MessageOrigin + originalSender
        uint256 bridgeId = _incomingBridgeId++;
        _bridgeRequests[bridgeId] = BridgeRequest({
            recipient: recipient,
            asset: localAsset,
            amount: localAmount,
            sourceChainId: sourceChainId,
            bridgeId: sourceBridgeId,
            messageId: messageId,
            status: BridgeRequestStatus.Pending,
            vaultQueueId: 0,
            origin: origin,
            originalSender: originalSender
        });

        // Check if recipient is valid EVM address
        if (!recipient.isValidEvmAddress()) {
            // Cannot transfer to non-EVM address on this chain - keep Pending
            emit BridgeRequestProcessed(
                bridgeId,
                0,
                localAsset,
                localAmount,
                recipient,
                BridgeRequestStatus.Pending,
                sourceChainId,
                sourceBridgeId
            );
            return true;
        }

        // Convert recipient to address and attempt draw from Vault with queue option
        address recipientAddr = recipient.bytes32ToAddress();
        DrawResult memory result = VAULT.draw(localAsset, localAmount, recipientAddr, true);

        if (result.status == DrawStatus.Queued) {
            // Request was queued in Vault
            _bridgeRequests[bridgeId].vaultQueueId = result.queueId;
            _bridgeRequests[bridgeId].status = BridgeRequestStatus.Queued;
            _vaultQueueIdToBridgeId[result.queueId] = bridgeId;

            emit BridgeRequestProcessed(
                bridgeId,
                result.queueId,
                localAsset,
                localAmount,
                recipient,
                BridgeRequestStatus.Queued,
                sourceChainId,
                sourceBridgeId
            );
        } else if (result.status == DrawStatus.Fulfilled) {
            // Immediate success - funds transferred directly to recipient
            _bridgeRequests[bridgeId].status = BridgeRequestStatus.Fulfilled;

            emit BridgeRequestFulfilled(bridgeId, recipientAddr, localAsset, localAmount, sourceChainId, sourceBridgeId);
        } else {
            // DrawStatus.Unfulfillable - transfer to recipient failed
            _bridgeRequests[bridgeId].status = BridgeRequestStatus.Unfulfillable;

            emit BridgeRequestUnfulfillable(bridgeId, sourceChainId, sourceBridgeId);
        }

        return true;
    }

    /**
     * @notice Send a bridge message to another chain
     * @dev Used by both bridge() for user-initiated bridges and cancelBridgeRequest() for refunds.
     *      `sender` is the EVM caller that triggered this dispatch (user on bridge(),
     *      canceller on cancelBridgeRequest()) and serves two purposes:
     *        - emitted as-is in BridgeInitiated for indexers / UI;
     *        - encoded as `bytes32(sender)` into the cross-chain payload and stored on the
     *          destination's `BridgeRequest.originalSender` as the refund target if that
     *          destination request is later cancelled.
     *      Both entry points have an EVM `msg.sender` so an `address` parameter is sufficient;
     *      the destination stores the value as `bytes32` to support non-EVM senders on routes
     *      that other source-chain contracts may inject in the future.
     * @param destChainId Destination chain ID
     * @param asset Asset address on this chain
     * @param amount Amount to bridge
     * @param recipient Recipient on destination chain (bytes32 for non-EVM support)
     * @param sender EVM caller that triggered this dispatch; recorded in event and payload
     * @param feeAmount The fee amount (for event emission, 0 for refunds)
     * @param presetId MBA preset to use (bytes32(0) = default)
     * @return bridgeId The unique bridge ID on this chain
     * @return messageId The cross-chain message ID
     */
    function _sendBridgeMessage(
        uint256 destChainId,
        address asset,
        uint256 amount,
        bytes32 recipient,
        address sender,
        uint256 feeAmount,
        bytes32 presetId
    ) internal returns (uint256 bridgeId, bytes32 messageId) {
        bridgeId = _outgoingBridgeId++;

        // Convert to shared decimals for cross-chain encoding
        uint256 sharedAmount = _toSharedDecimals(asset, amount);
        if (sharedAmount == 0) revert AmountTooSmall();

        // Compute dust (amount lost to rounding)
        uint256 actualBridgeAmount = _toLocalDecimals(asset, sharedAmount);
        uint256 dustAmount = amount - actualBridgeAmount;
        if (dustAmount > 0) {
            emit DustRemoved(asset, dustAmount);
        }

        // Encode payload (recipient, sourceAsset, sharedAmount, sourceBridgeId, originalSender) and send
        {
            bytes memory payload =
                abi.encode(recipient, asset.addressToBytes32(), sharedAmount, bridgeId, sender.addressToBytes32());
            (, uint256[] memory adapterValues) =
                CROSS_MESSAGE_CONTROLLER.estimateFees(destChainId, payload, MessageType.BRIDGE, presetId);
            // TODO(audit-#210): replace the hardcoded 0 with the bridge's
            // USD-priced value (asset 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.
            // https://github.com/Yei-Finance/clovis/issues/210
            messageId = CROSS_MESSAGE_CONTROLLER.sendMessage{value: msg.value}(
                destChainId, payload, MessageType.BRIDGE, adapterValues, presetId, 0
            );
        }

        emit BridgeInitiated(messageId, sender, asset, bridgeId, actualBridgeAmount, destChainId, recipient, feeAmount);
    }

    /**
     * @notice Safe transfer in tokens, handling fee-on-transfer tokens
     * @param asset Address of the token
     * @param from Address to transfer from
     * @param amount Amount requested to transfer
     * @return Actual amount received after transfer
     */
    function _doTransferIn(address asset, address from, uint256 amount) internal returns (uint256) {
        uint256 balanceBefore = IERC20(asset).balanceOf(address(this));
        IERC20(asset).safeTransferFrom(from, address(this), amount);
        return IERC20(asset).balanceOf(address(this)) - balanceBefore;
    }

    /**
     * @notice Internal helper to set an asset mapping
     * @dev Maintains the per-local-asset reverse index so `removeSupportedAsset` can
     *      reject removing an asset that still has inbound mappings. If the same pair
     *      previously pointed at a different local asset, the old reverse entry is
     *      removed before the new one is registered.
     * @param sourceChainId Source chain ID
     * @param sourceAsset Source asset as bytes32
     * @param localAsset Local asset address
     */
    function _setAssetMapping(uint256 sourceChainId, bytes32 sourceAsset, address localAsset) internal {
        if (sourceAsset == bytes32(0)) revert ZeroAddress();
        if (localAsset == address(0)) revert ZeroAddress();

        bytes32 key = _mappingKey(sourceChainId, sourceAsset);
        address previousLocal = _assetMappings[sourceChainId][sourceAsset];
        if (previousLocal != address(0) && previousLocal != localAsset) {
            _assetMappingsByLocal[previousLocal].remove(key);
        }
        _assetMappings[sourceChainId][sourceAsset] = localAsset;
        _assetMappingsByLocal[localAsset].add(key);

        emit AssetMappingSet(sourceChainId, sourceAsset, localAsset);
    }

    function _estimateBridgeFee(address asset, uint256 amount, uint256 destChainId, bytes32 recipient, bytes32 presetId)
        internal
        view
        returns (uint256 totalFee, uint256[] memory adapterFees)
    {
        uint256 sharedAmount = _toSharedDecimals(asset, amount);
        bytes memory payload =
            abi.encode(recipient, asset.addressToBytes32(), sharedAmount, uint256(0), msg.sender.addressToBytes32());
        return CROSS_MESSAGE_CONTROLLER.estimateFees(destChainId, payload, MessageType.BRIDGE, presetId);
    }

    /**
     * @notice Get preset fee in basis points
     * @param destChainId Destination chain ID
     * @param presetId Preset to read fee from (bytes32(0) = default)
     * @return feeBps Fee in basis points
     */
    function _getPresetFeeBps(uint256 destChainId, bytes32 presetId) internal view returns (uint256 feeBps) {
        bytes32 resolvedPresetId =
            presetId == bytes32(0) ? CROSS_MESSAGE_CONTROLLER.getDefaultPreset(destChainId) : presetId;
        if (resolvedPresetId == bytes32(0)) return 0;
        feeBps = CROSS_MESSAGE_CONTROLLER.getPresetFee(resolvedPresetId);
    }

    /**
     * @notice Resolve the local asset address from a source chain asset
     * @dev Requires an explicit `_assetMappings` entry and that the resolved asset
     *      is currently in `_supportedAssets`. No same-address fall-through.
     * @param sourceChainId Source chain ID
     * @param sourceAsset Source asset as bytes32 (supports both EVM and non-EVM)
     * @return localAsset The local asset address
     */
    function _resolveLocalAsset(uint256 sourceChainId, bytes32 sourceAsset) internal view returns (address localAsset) {
        localAsset = _assetMappings[sourceChainId][sourceAsset];
        if (localAsset == address(0)) revert UnsupportedAsset(address(0));
        if (!_supportedAssets.contains(localAsset)) revert UnsupportedAsset(localAsset);
    }

    function _toSharedDecimals(address asset, uint256 localAmount) internal view returns (uint256) {
        uint8 sd = _sharedDecimals[asset];
        if (sd == 0) revert SharedDecimalsNotSet(asset);
        uint8 localDecimals = IERC20Metadata(asset).decimals();
        if (localDecimals == sd) return localAmount;
        return localAmount / 10 ** (localDecimals - sd);
    }

    function _toLocalDecimals(address localAsset, uint256 sharedAmount) internal view returns (uint256) {
        uint8 sd = _sharedDecimals[localAsset];
        if (sd == 0) revert SharedDecimalsNotSet(localAsset);
        uint8 localDecimals = IERC20Metadata(localAsset).decimals();
        if (localDecimals == sd) return sharedAmount;
        return sharedAmount * 10 ** (localDecimals - sd);
    }

    function _validateSharedDecimals(address asset, uint8 sharedDecimals_) internal view {
        if (sharedDecimals_ < 1 || sharedDecimals_ > 18) revert InvalidSharedDecimals(sharedDecimals_, 18);
        uint8 localDecimals = IERC20Metadata(asset).decimals();
        if (sharedDecimals_ > localDecimals) revert InvalidSharedDecimals(sharedDecimals_, localDecimals);
    }

    /**
     * @notice Validate that a bridge request can be cancelled by the caller
     * @dev Checks authorization (recipient or admin) and status (Queued, Unfulfillable, or Pending for non-EVM)
     * @param request The bridge request to validate
     * @param bridgeId The bridge ID (for error messages)
     */
    function _validateCancellation(BridgeRequest storage request, uint256 bridgeId) internal view {
        // Check authorization: recipient (converted to address) OR BRIDGE_ADMIN_ROLE (for non-EVM)
        bool isRecipient = false;
        if (request.recipient.isValidEvmAddress()) {
            isRecipient = msg.sender == request.recipient.bytes32ToAddress();
        }
        bool isAdmin = ACCESS_CONTROL.hasRole(BRIDGE_ADMIN_ROLE, msg.sender);

        if (!isRecipient && !isAdmin) revert NotAuthorized();

        // Check status: must be Queued, Unfulfillable, OR (Pending AND non-EVM recipient)
        bool canCancel = request.status == BridgeRequestStatus.Queued
            || request.status == BridgeRequestStatus.Unfulfillable
            || (request.status == BridgeRequestStatus.Pending && !request.recipient.isValidEvmAddress());

        if (!canCancel) revert BridgeRequestNotCancellable(bridgeId);
    }

    function _mappingKey(uint256 sourceChainId, bytes32 sourceAsset) internal pure returns (bytes32) {
        return keccak256(abi.encode(sourceChainId, sourceAsset));
    }
}

src/protocol/bridge/interfaces/IBridgeVaultApp.sol

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

import {IVault} from "../../vault/interfaces/IVault.sol";
import {IIncomeCollector} from "../../incomeCollector/interfaces/IIncomeCollector.sol";
import {IAttestationService} from "../../attestation/interfaces/IAttestationService.sol";
import {Attestation} from "../../attestation/AttestationTypes.sol";
import {MessageOrigin} from "../../mba/libraries/MessageLib.sol";

/**
 * @title IBridgeVaultApp
 * @author Clovis Protocol
 * @notice Interface for the BridgeVaultApp contract
 * @dev Pool-based bridge that uses Vault liquidity for cross-chain asset transfers
 */
interface IBridgeVaultApp {
    /// @notice Status of a bridge request on the destination chain
    enum BridgeRequestStatus {
        Pending, // Just received OR non-EVM recipient awaiting admin refund action
        Queued, // Queued in Vault (EVM recipient only)
        Fulfilled, // Successfully fulfilled
        Cancelled, // Cancelled by user (refunded to source)
        Unfulfillable // Transfer to recipient failed; awaiting admin redirect
    }

    /// @notice A bridge request stored on the destination chain
    /// @param recipient Original recipient (bytes32 for non-EVM support)
    /// @param asset Asset address on this chain
    /// @param amount Amount to be transferred
    /// @param sourceChainId Source chain ID
    /// @param bridgeId Bridge ID from source chain (unique per sourceChainId)
    /// @param messageId Cross-chain message ID
    /// @param status Request status
    /// @param vaultQueueId Vault's queue ID (0 if not queued in Vault / non-EVM)
    /// @param origin Source chain metadata (used by MessageHandler for peer validation)
    /// @param originalSender Address that initiated the bridge on the source chain;
    ///        used as the refund recipient if the request is cancelled. Stored as `bytes32`
    ///        so non-EVM senders (e.g., Solana pubkeys) survive the cross-chain round-trip.
    ///        `origin.sourceSender` is the source-side `BridgeVaultApp` contract, not the
    ///        user, and must not be used as a refund target.
    struct BridgeRequest {
        bytes32 recipient;
        address asset;
        uint256 amount;
        uint256 sourceChainId;
        uint256 bridgeId;
        bytes32 messageId;
        BridgeRequestStatus status;
        uint256 vaultQueueId;
        MessageOrigin origin;
        bytes32 originalSender;
    }

    /// @notice Parameters for initiating a bridge transfer
    /// @param asset Source asset address
    /// @param amount Amount to bridge
    /// @param destChainId Destination chain ID
    /// @param recipient Recipient on destination (bytes32 for flexibility)
    struct BridgeParams {
        address asset;
        uint256 amount;
        uint256 destChainId;
        bytes32 recipient;
    }

    /// @notice Emitted when a bridge transfer is initiated on the source chain
    /// @param messageId The cross-chain message ID
    /// @param sender The address initiating the bridge
    /// @param asset The asset being bridged
    /// @param bridgeId The unique bridge ID on this chain
    /// @param amount The amount being bridged
    /// @param destChainId The destination chain ID
    /// @param recipient The recipient on the destination chain
    /// @param feeAmount The fee charged for the bridge
    event BridgeInitiated(
        bytes32 indexed messageId,
        address indexed sender,
        address indexed asset,
        uint256 bridgeId,
        uint256 amount,
        uint256 destChainId,
        bytes32 recipient,
        uint256 feeAmount
    );

    /// @notice Emitted when a bridge request is queued or marked pending on destination chain
    /// @dev Only emitted when status is Queued or Pending, NOT when immediately fulfilled
    /// @param bridgeId The unique bridge ID on this chain (local)
    /// @param vaultQueueId The Vault's queue ID (0 if non-EVM/Pending)
    /// @param asset The asset being transferred
    /// @param amount The amount to transfer
    /// @param recipient The intended recipient
    /// @param status The initial status of the request (Queued or Pending only)
    /// @param sourceChainId The source chain ID where bridge was initiated
    /// @param sourceBridgeId The bridge ID on the source chain
    event BridgeRequestProcessed(
        uint256 indexed bridgeId,
        uint256 indexed vaultQueueId,
        address indexed asset,
        uint256 amount,
        bytes32 recipient,
        BridgeRequestStatus status,
        uint256 sourceChainId,
        uint256 sourceBridgeId
    );

    /// @notice Emitted when a bridge request is fulfilled (immediate or from queue)
    /// @param bridgeId The bridge ID of the fulfilled request (local)
    /// @param recipient The actual recipient who received the funds (EVM address)
    /// @param asset The asset transferred
    /// @param amount The amount transferred
    /// @param sourceChainId The source chain ID where bridge was initiated
    /// @param sourceBridgeId The bridge ID on the source chain
    event BridgeRequestFulfilled(
        uint256 indexed bridgeId,
        address recipient,
        address asset,
        uint256 amount,
        uint256 sourceChainId,
        uint256 sourceBridgeId
    );

    /// @notice Emitted when a bridge request cannot be fulfilled (transfer failed)
    /// @param bridgeId The bridge ID of the unfulfillable request (local)
    /// @param sourceChainId The source chain ID where bridge was initiated
    /// @param sourceBridgeId The bridge ID on the source chain
    event BridgeRequestUnfulfillable(uint256 indexed bridgeId, uint256 sourceChainId, uint256 sourceBridgeId);

    /// @notice Emitted when a bridge request is cancelled and refund is initiated
    /// @param bridgeId The bridge ID of the cancelled request (local)
    /// @param refundRecipient The original sender on source chain who will receive refund
    /// @param sourceChainId The source chain ID where bridge was initiated
    /// @param sourceBridgeId The bridge ID on the source chain
    event BridgeRequestCancelled(
        uint256 indexed bridgeId, bytes32 refundRecipient, uint256 sourceChainId, uint256 sourceBridgeId
    );

    /// @notice Emitted when the bridge fee for an asset is updated
    /// @param asset The asset address
    /// @param feePercent The new fee in basis points
    event BridgeFeeSet(address indexed asset, uint256 feePercent);

    /// @notice Emitted when an asset is added to the supported assets list
    /// @param asset The asset address
    /// @param symbol The asset symbol
    /// @param decimals The asset decimals
    event AssetAdded(address indexed asset, string symbol, uint8 decimals);

    /// @notice Emitted when an asset is removed from the supported assets list
    /// @param asset The asset address
    event AssetRemoved(address indexed asset);

    /// @notice Emitted when shared decimals are configured for an asset
    /// @param asset The asset address
    /// @param sharedDecimals The shared decimal precision for cross-chain encoding
    event SharedDecimalsSet(address indexed asset, uint8 sharedDecimals);

    /// @notice Emitted when dust is removed during source-side encoding
    /// @param asset The asset address
    /// @param amount The dust amount lost to rounding
    event DustRemoved(address indexed asset, uint256 amount);

    /// @notice Emitted when the income collector is updated
    /// @param previousCollector The previous income collector address
    /// @param newCollector The new income collector address
    event IncomeCollectorSet(address indexed previousCollector, address indexed newCollector);

    /// @notice Emitted when collected fees are transferred to the income collector
    /// @param asset The asset for which fees were 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 an asset mapping is configured for cross-chain transfers
    /// @param sourceChainId The source chain ID
    /// @param sourceAsset The asset address on the source chain (bytes32 for non-EVM support)
    /// @param localAsset The corresponding asset address on this chain
    event AssetMappingSet(uint256 indexed sourceChainId, bytes32 indexed sourceAsset, address indexed localAsset);

    /// @notice Emitted when an asset mapping is removed
    /// @param sourceChainId The source chain ID
    /// @param sourceAsset The asset address on the source chain (bytes32 for non-EVM support)
    /// @param localAsset The local asset that was mapped
    event AssetMappingRemoved(uint256 indexed sourceChainId, bytes32 indexed sourceAsset, address indexed localAsset);

    /// @notice Emitted when the bridge is paused
    /// @param guardian The address that paused the bridge
    event BridgePaused(address indexed guardian);

    /// @notice Emitted when the bridge is unpaused
    /// @param admin The address that unpaused the bridge
    event BridgeUnpaused(address indexed admin);

    /// @notice Emitted when the attestation service is updated
    /// @param previousService The previous attestation service address
    /// @param newService The new attestation service address
    event AttestationServiceSet(address indexed previousService, address indexed newService);

    /// @notice Emitted when an admin sweeps ERC20 dust out of the contract
    /// @param token The token swept
    /// @param recipient The address that received the swept tokens
    /// @param amount The amount swept
    event TokensRescued(address indexed token, address indexed recipient, uint256 amount);

    /// @notice Initialize the BridgeVaultApp
    /// @param incomeCollector_ The IncomeCollector contract address
    /// @param attestationService_ The AttestationService contract address
    function initialize(address incomeCollector_, address attestationService_) external;

    /// @notice Initiate a cross-chain bridge transfer with explicit preset
    /// @param attestation Attestation proving the transaction is authorized
    /// @param asset The asset to bridge
    /// @param amount The amount to bridge
    /// @param destChainId The destination chain ID
    /// @param recipient The recipient address on the destination chain (bytes32 for non-EVM support)
    /// @param presetId MBA preset to use (bytes32(0) = default)
    /// @return messageId The cross-chain message ID
    function bridge(
        Attestation calldata attestation,
        address asset,
        uint256 amount,
        uint256 destChainId,
        bytes32 recipient,
        bytes32 presetId
    ) external payable returns (bytes32 messageId);

    /// @notice Initiate a cross-chain bridge transfer with an explicit cancel-refund target.
    /// @dev Additive overload for contract integrators. `cancelAddress` is stamped as the
    ///      cross-chain payload's `originalSender` (the dest-side refund target if the bridge
    ///      request is later cancelled), in place of `msg.sender`. This lets a contract that
    ///      calls `bridge` on a user's behalf direct a cancel-refund to the real end-user
    ///      rather than to itself. Funds-in stays from `msg.sender`; `cancelAddress` is only
    ///      the refund target, distinct from who funds the bridge.
    /// @dev `cancelAddress` is attester-bound: because it is a real function parameter it is
    ///      part of `msg.data` and therefore covered by the signed attestation digest. A caller
    ///      cannot substitute a different `cancelAddress` without a fresh attester signature.
    /// @param attestation Attestation proving the transaction is authorized
    /// @param asset The asset to bridge
    /// @param amount The amount to bridge
    /// @param destChainId The destination chain ID
    /// @param recipient The recipient address on the destination chain (bytes32 for non-EVM support)
    /// @param presetId MBA preset to use (bytes32(0) = default)
    /// @param cancelAddress Address that receives the source-chain refund if the request is
    ///        cancelled on the destination chain. Must be non-zero.
    /// @return messageId The cross-chain message ID
    function bridge(
        Attestation calldata attestation,
        address asset,
        uint256 amount,
        uint256 destChainId,
        bytes32 recipient,
        bytes32 presetId,
        address cancelAddress
    ) external payable returns (bytes32 messageId);

    /// @notice Initiate a cross-chain bridge transfer using default preset
    /// @param attestation Attestation proving the transaction is authorized
    /// @param asset The asset to bridge
    /// @param amount The amount to bridge
    /// @param destChainId The destination chain ID
    /// @param recipient The recipient address on the destination chain (bytes32 for non-EVM support)
    /// @return messageId The cross-chain message ID
    function bridge(
        Attestation calldata attestation,
        address asset,
        uint256 amount,
        uint256 destChainId,
        bytes32 recipient
    ) external payable returns (bytes32 messageId);

    /// @notice Cancel a bridge request and initiate refund to source chain
    /// @dev Caller must be the recipient (converted to address) or BRIDGE_ADMIN_ROLE (for non-EVM)
    /// @dev Request must be Queued or (Pending AND non-EVM recipient)
    /// @param attestation Attestation proving the transaction is authorized
    /// @param bridgeId The ID of the bridge request to cancel (local bridge ID on this chain)
    /// @return refundBridgeId The new bridge ID for the refund transaction
    function cancelBridgeRequest(Attestation calldata attestation, uint256 bridgeId)
        external
        payable
        returns (uint256 refundBridgeId);

    /// @notice Drop a bridge request without sending a refund
    /// @dev Admin-only function for Pending requests (non-EVM recipients)
    /// @dev Marks as Cancelled without triggering refund to source chain
    /// @dev Funds remain in Vault allocated to this app
    /// @param bridgeId The ID of the bridge request to drop
    function dropBridgeRequest(uint256 bridgeId) external;

    /// @notice Set the bridge fee for an asset
    /// @param asset The asset address
    /// @param feePercent The fee in basis points (e.g., 100 = 1%)
    function setBridgeFee(address asset, uint256 feePercent) external;

    /// @notice Add an asset to the supported assets list
    /// @param asset The asset address to add
    /// @param sharedDecimals_ The shared decimal precision for cross-chain encoding
    function addSupportedAsset(address asset, uint8 sharedDecimals_) external;

    /// @notice Remove an asset from the supported assets list
    /// @param asset The asset address to remove
    function removeSupportedAsset(address asset) external;

    /// @notice Set shared decimals for an existing supported asset (migration helper)
    /// @param asset The asset address
    /// @param sharedDecimals_ The shared decimal precision for cross-chain encoding
    function setSharedDecimals(address asset, uint8 sharedDecimals_) external;

    /// @notice Set the asset mapping for cross-chain transfers
    /// @param sourceChainId The source chain ID
    /// @param sourceAsset The asset address on the source chain (bytes32 for non-EVM support)
    /// @param localAsset The corresponding asset address on this chain
    function setAssetMapping(uint256 sourceChainId, bytes32 sourceAsset, address localAsset) external;

    /// @notice Remove an asset mapping for cross-chain transfers
    /// @param sourceChainId The source chain ID
    /// @param sourceAsset The asset address on the source chain (bytes32 for non-EVM support)
    function removeAssetMapping(uint256 sourceChainId, bytes32 sourceAsset) external;

    /// @notice Set the income collector address
    /// @param collector The new income collector address
    function setIncomeCollector(address collector) external;

    /// @notice Set the attestation service address
    /// @param attestationService_ The new attestation service address
    function setAttestationService(address attestationService_) external;

    /// @notice One-time backfill of the per-local-asset reverse index for a pre-existing
    ///         asset mapping. Reads the current `_assetMappings[sourceChainId][sourceAsset]`
    ///         entry and re-registers it in `_assetMappingsByLocal`. Idempotent and safe to
    ///         call after the upgrade for every historical mapping pair.
    /// @dev Required on chains that already have asset mappings configured before this
    ///      contract version was deployed.
    /// @param sourceChainId Source chain ID of the existing mapping
    /// @param sourceAsset Source asset (bytes32) of the existing mapping
    function backfillAssetMapping(uint256 sourceChainId, bytes32 sourceAsset) external;

    /// @notice Collect accumulated fees for an asset and transfer to income collector
    /// @param asset The asset for which to collect fees
    function collectFees(address asset) external;

    /// @notice Sweep ERC20 tokens that don't belong to outstanding fee accounting.
    /// @dev Only callable by BRIDGE_ADMIN_ROLE. Refuses to dip into the slice of
    ///      `balanceOf(this)` reserved by `_collectedBridgeFees[token] + _collectedPresetFees[token]`, so pending fees
    ///      stay routable through `collectFees`. Use to recover refund/cancel
    ///      residues, accidental ERC20 transfers, or leftover dust after asset
    ///      removal. The protected guard applies to every token — not just the
    ///      currently-supported asset set — because a previously-supported asset
    ///      may still carry uncollected fees.
    /// @param token The ERC20 token to rescue
    /// @param recipient The address to receive the rescued tokens
    /// @param amount The amount to rescue
    function rescueTokens(address token, address recipient, uint256 amount) external;

    /// @notice Pause the bridge
    /// @dev Only callable by BRIDGE_GUARDIAN_ROLE. Returns without effect when already paused (YEI-1006)
    function pauseBridge() external;

    /// @notice Unpause the bridge
    /// @dev Only callable by UNPAUSER_ROLE, the one role that gates every unpause in the protocol (YEI-1006)
    function unpauseBridge() external;

    /// @notice Estimate the cross-chain fee for a bridge transfer with explicit preset
    /// @param asset The asset to bridge
    /// @param amount The amount to bridge
    /// @param destChainId The destination chain ID
    /// @param recipient The recipient address on the destination 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 estimateBridgeFee(address asset, uint256 amount, uint256 destChainId, bytes32 recipient, bytes32 presetId)
        external
        view
        returns (uint256 totalFee, uint256[] memory adapterFees);

    /// @notice Estimate the cross-chain fee for a bridge transfer using default preset
    /// @param asset The asset to bridge
    /// @param amount The amount to bridge
    /// @param destChainId The destination chain ID
    /// @param recipient The recipient address on the destination chain
    /// @return totalFee Total fee in native token
    /// @return adapterFees Individual fees per messaging adapter
    function estimateBridgeFee(address asset, uint256 amount, uint256 destChainId, bytes32 recipient)
        external
        view
        returns (uint256 totalFee, uint256[] memory adapterFees);

    /// @notice Estimate the cross-chain fee for cancelling a bridge request
    /// @dev The cancellation sends a refund message to the source chain
    /// @param bridgeId The bridge request ID to cancel
    /// @return totalFee Total fee in native token
    /// @return adapterFees Individual fees per messaging adapter
    function estimateCancelBridgeRequestFee(uint256 bridgeId)
        external
        view
        returns (uint256 totalFee, uint256[] memory adapterFees);

    /// @notice Get the shared decimals for an asset
    /// @param asset The asset address
    /// @return The shared decimal precision
    function getSharedDecimals(address asset) external view returns (uint8);

    /// @notice Get a bridge request by ID
    /// @param bridgeId The ID of the bridge request
    /// @return The bridge request details
    function getBridgeRequest(uint256 bridgeId) external view returns (BridgeRequest memory);

    /// @notice Get the bridge fee for an asset
    /// @param asset The asset address
    /// @return The fee in basis points
    function getBridgeFee(address asset) external view returns (uint256);

    /// @notice Get the total collected fees for an asset
    /// @param asset The asset address
    /// @return The total collected fees
    function getCollectedFees(address asset) external view returns (uint256);

    /// @notice Check if an asset is supported for bridging
    /// @param asset The asset address
    /// @return True if the asset is supported
    function isSupportedAsset(address asset) external view returns (bool);

    /// @notice Get the local asset address for a source chain asset
    /// @param sourceChainId The source chain ID
    /// @param sourceAsset The asset address on the source chain (bytes32 for non-EVM support)
    /// @return The corresponding asset address on this chain
    function getAssetMapping(uint256 sourceChainId, bytes32 sourceAsset) external view returns (address);

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

    /// @notice Get the income collector contract address
    /// @return The IncomeCollector contract
    function incomeCollector() external view returns (IIncomeCollector);

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

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

    /// @notice Get the available liquidity for a source chain asset
    /// @param sourceChainId The source chain ID
    /// @param sourceAsset The asset address on the source chain (bytes32 for non-EVM support)
    /// @return The available liquidity on this chain
    function getAvailableLiquidity(uint256 sourceChainId, bytes32 sourceAsset) external view returns (uint256);
}

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/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.