Skip to content
Verified contractPartialBUSL-1.1

VaultRouter

Address0x5bd445d7e115bb5d170d521f193255b3802029be
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 1 runs
EVM version
cancun
License
BUSL-1.1
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,282,894
Creation transaction
0x4fe23fc3cb…e1b4142ab0

63 files

src/vaults/VaultRouter.sol

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

import {BaseSyncDepositVault} from "./BaseVaults.sol";
import {IBaseVault} from "./interfaces/IBaseVault.sol";
import {IAsyncVault} from "./interfaces/IAsyncVault.sol";
import {IVaultRouter} from "./interfaces/IVaultRouter.sol";

import {Auth} from "../misc/Auth.sol";
import {Multicall} from "../misc/Multicall.sol";
import {Recoverable} from "../misc/Recoverable.sol";
import {CastLib} from "../misc/libraries/CastLib.sol";
import {IERC7540Deposit} from "../misc/interfaces/IERC7540.sol";
import {IERC20, IERC20Permit} from "../misc/interfaces/IERC20.sol";
import {SafeTransferLib} from "../misc/libraries/SafeTransferLib.sol";

import {PoolId} from "../core/types/PoolId.sol";
import {ISpoke} from "../core/spoke/interfaces/ISpoke.sol";
import {ShareClassId} from "../core/types/ShareClassId.sol";
import {VaultDetails, ISpokeRegistry} from "../core/spoke/interfaces/ISpokeRegistry.sol";

import {IShareToken} from "../token/interfaces/IShareToken.sol";

/// @title  VaultRouter
/// @notice This is a helper contract, designed to be the entrypoint for EOAs.
///         It removes the need to know about all other contracts and simplifies the way to interact with the protocol.
///         It bundles several calls into one transaction via multicall, each dispatching its own cross-chain
///         message. Investment requests are paid for by the pool through the request manager, so the caller
///         should not attach native tokens for them: any value sent for such a call stays in the router
///         and is only recoverable via `Recoverable`.
/// @dev    It is critical to ensure that at the end of any transaction, no funds remain in the
///         VaultRouter. Any funds that do remain are at risk of being taken by other users.
contract VaultRouter is Multicall, Recoverable, IVaultRouter {
    using CastLib for address;

    /// @dev Requests for Centrifuge pool are non-fungible and all have ID = 0
    uint256 private constant REQUEST_ID = 0;

    ISpoke public immutable spoke;
    ISpokeRegistry public immutable spokeRegistry;

    constructor(ISpoke spoke_, ISpokeRegistry spokeRegistry_, address deployer) Auth(deployer) {
        spoke = spoke_;
        spokeRegistry = spokeRegistry_;
    }

    //----------------------------------------------------------------------------------------------
    // Enable interactions
    //----------------------------------------------------------------------------------------------

    function enable(IBaseVault vault) public payable protected {
        vault.setEndorsedOperator(msg.sender, true);
    }

    function disable(IBaseVault vault) external payable protected {
        vault.setEndorsedOperator(msg.sender, false);
    }

    //----------------------------------------------------------------------------------------------
    // Deposit
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IVaultRouter
    function requestDeposit(IAsyncVault vault, uint256 amount, address controller, address owner)
        external
        payable
        protected
    {
        require(owner == msg.sender || owner == address(this), InvalidOwner());

        VaultDetails memory vaultDetails = spokeRegistry.vaultDetails(address(vault));
        require(vaultDetails.asset != address(0), ISpokeRegistry.UnknownVault());
        if (owner == address(this)) {
            _approveMax(vaultDetails.asset, address(vault));
        }

        vault.requestDeposit(amount, controller, owner);
    }

    /// @inheritdoc IVaultRouter
    function deposit(BaseSyncDepositVault vault, uint256 assets, address receiver, address owner)
        external
        payable
        protected
    {
        require(owner == msg.sender || owner == address(this), InvalidOwner());
        require(!vault.supportsInterface(type(IERC7540Deposit).interfaceId), NonSyncDepositVault());
        require(vault.isPermissioned(msg.sender), InvalidSender());

        VaultDetails memory vaultDetails = spokeRegistry.vaultDetails(address(vault));
        require(vaultDetails.asset != address(0), ISpokeRegistry.UnknownVault());
        if (owner != address(this)) SafeTransferLib.safeTransferFrom(vaultDetails.asset, owner, address(this), assets);
        _approveMax(vaultDetails.asset, address(vault));

        vault.deposit(assets, receiver);
    }

    /// @inheritdoc IVaultRouter
    function crosschainTransferShares(
        BaseSyncDepositVault vault,
        uint128 shares,
        uint16 centrifugeId,
        bytes32 receiver,
        address owner,
        uint128 extraGasLimit,
        uint128 remoteExtraGasLimit,
        address refund
    ) external payable protected {
        require(owner == msg.sender || owner == address(this), InvalidOwner());
        require(spokeRegistry.isVaultRegistered(address(vault)), ISpokeRegistry.UnknownVault());

        address share_ = vault.share();
        if (owner != address(this)) SafeTransferLib.safeTransferFrom(share_, owner, address(this), shares);
        _approveMax(share_, address(spoke));
        _crosschainTransferShares(
            spokeRegistry.vaultDetails(address(vault)),
            shares,
            centrifugeId,
            receiver,
            owner,
            extraGasLimit,
            remoteExtraGasLimit,
            refund
        );
    }

    /// @dev Split out of {crosschainTransferShares} to avoid a stack-too-deep: the outer frame holds
    ///      eight parameters plus the vault-validity check, which together exceed the stack limit.
    function _crosschainTransferShares(
        VaultDetails memory vaultDetails,
        uint128 shares,
        uint16 centrifugeId,
        bytes32 receiver,
        address owner,
        uint128 extraGasLimit,
        uint128 remoteExtraGasLimit,
        address refund
    ) internal {
        spoke.crosschainTransferShares{value: msg.value}(
            centrifugeId,
            vaultDetails.poolId,
            vaultDetails.scId,
            receiver,
            owner,
            address(this),
            shares,
            extraGasLimit,
            remoteExtraGasLimit,
            refund
        );
    }

    /// @inheritdoc IVaultRouter
    function claimDeposit(IAsyncVault vault, address receiver, address controller) external payable protected {
        _canClaim(vault, receiver, controller);
        uint256 maxMint = vault.maxMint(controller);
        vault.mint(maxMint, receiver, controller);
    }

    /// @inheritdoc IVaultRouter
    function cancelDepositRequest(IAsyncVault vault) external payable protected {
        vault.cancelDepositRequest(REQUEST_ID, msg.sender);
    }

    /// @inheritdoc IVaultRouter
    function claimCancelDepositRequest(IAsyncVault vault, address receiver, address controller)
        external
        payable
        protected
    {
        _canClaim(vault, receiver, controller);
        vault.claimCancelDepositRequest(REQUEST_ID, receiver, controller);
    }

    //----------------------------------------------------------------------------------------------
    // Redeem
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IVaultRouter
    function requestRedeem(IAsyncVault vault, uint256 amount, address controller, address owner)
        external
        payable
        protected
    {
        require(owner == msg.sender || owner == address(this), InvalidOwner());
        vault.requestRedeem(amount, controller, owner);
    }

    /// @inheritdoc IVaultRouter
    function claimRedeem(IBaseVault vault, address receiver, address controller) external payable protected {
        _canClaim(vault, receiver, controller);
        uint256 maxWithdraw = vault.maxWithdraw(controller);
        vault.withdraw(maxWithdraw, receiver, controller);
    }

    /// @inheritdoc IVaultRouter
    function cancelRedeemRequest(IAsyncVault vault) external payable protected {
        vault.cancelRedeemRequest(REQUEST_ID, msg.sender);
    }

    /// @inheritdoc IVaultRouter
    function claimCancelRedeemRequest(IAsyncVault vault, address receiver, address controller)
        external
        payable
        protected
    {
        _canClaim(vault, receiver, controller);
        vault.claimCancelRedeemRequest(REQUEST_ID, receiver, controller);
    }

    //----------------------------------------------------------------------------------------------
    // ERC-20 permits
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IVaultRouter
    function permit(address asset, address spender, uint256 assets, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
        external
        payable
        protected
    {
        try IERC20Permit(asset).permit(msg.sender, spender, assets, deadline, v, r, s) {} catch {}
    }

    //----------------------------------------------------------------------------------------------
    // View methods
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IVaultRouter
    function getVault(PoolId poolId, ShareClassId scId, address asset) external view returns (address vault_) {
        IShareToken share = IShareToken(address(spokeRegistry.shareToken(poolId, scId)));
        require(address(share) != address(0), ISpokeRegistry.ShareTokenDoesNotExist());

        vault_ = share.vault(asset);
        if (vault_ == address(0)) return address(0);

        VaultDetails memory details = spokeRegistry.vaultDetails(vault_);
        require(
            details.isLinked && details.poolId == poolId && details.scId == scId && details.asset == asset
                && details.tokenId == 0,
            ISpokeRegistry.InvalidVault()
        );
    }

    /// @inheritdoc IVaultRouter
    function hasPermissions(IBaseVault vault, address controller) external view returns (bool) {
        return vault.isPermissioned(controller);
    }

    /// @inheritdoc IVaultRouter
    function isEnabled(IBaseVault vault, address controller) public view returns (bool) {
        return vault.isOperator(controller, address(this));
    }

    /// @notice Gives the max approval to `to` for spending the given `asset` if not already approved.
    /// @dev    Assumes that `type(uint256).max` is large enough to never have to increase the allowance again.
    function _approveMax(address asset, address spender) internal {
        if (IERC20(asset).allowance(address(this), spender) == 0) {
            SafeTransferLib.safeApprove(asset, spender, type(uint256).max);
        }
    }

    /// @notice Ensures msg.sender is either the controller, or can permissionlessly claim
    ///         on behalf of the controller.
    function _canClaim(IBaseVault vault, address receiver, address controller) internal view {
        require(controller == msg.sender || (controller == receiver && isEnabled(vault, controller)), InvalidSender());
    }
}

lib/forge-std/src/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2;

interface IERC165 {
    /// @notice Query if a contract implements an interface
    /// @param interfaceID The interface identifier, as specified in ERC-165
    /// @dev Interface identification is specified in ERC-165. This function
    /// uses less than 30,000 gas.
    /// @return `true` if the contract implements `interfaceID` and
    /// `interfaceID` is not 0xffffffff, `false` otherwise
    function supportsInterface(bytes4 interfaceID) external view returns (bool);
}

src/admin/interfaces/IRoot.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {IScheduleAuth} from "../../core/messaging/interfaces/IScheduleAuth.sol";
import {IProtocolPauser} from "../../core/messaging/interfaces/IProtocolPauser.sol";

interface IRoot is IProtocolPauser, IScheduleAuth {
    //----------------------------------------------------------------------------------------------
    // Events
    //----------------------------------------------------------------------------------------------

    event File(bytes32 indexed what, uint256 data);
    event RelyContract(address indexed target, address indexed user);
    event DenyContract(address indexed target, address indexed user);
    event Endorse(address indexed user);
    event Veto(address indexed user);

    //----------------------------------------------------------------------------------------------
    // Errors
    //----------------------------------------------------------------------------------------------

    error DelayTooLong();
    error FileUnrecognizedParam();
    error TargetNotScheduled();
    error TargetNotReady();

    //----------------------------------------------------------------------------------------------
    // View methods
    //----------------------------------------------------------------------------------------------

    /// @notice Returns the current timelock for adding new wards
    function delay() external view returns (uint256);

    /// @notice Trusted contracts within the system
    function endorsements(address target) external view returns (uint256);

    /// @notice Returns when `relyTarget` has passed the timelock
    function schedule(address relyTarget) external view returns (uint256 timestamp);

    //----------------------------------------------------------------------------------------------
    // Administration
    //----------------------------------------------------------------------------------------------

    /// @notice Updates a contract parameter
    /// @param what Accepts a bytes32 representation of 'delay'
    function file(bytes32 what, uint256 data) external;

    //----------------------------------------------------------------------------------------------
    // Endorsements
    //----------------------------------------------------------------------------------------------

    /// @notice Endorses the `user`
    /// @dev    Endorsed users are trusted contracts in the system. They are allowed to bypass
    ///         token restrictions (e.g. the Escrow can automatically receive share class tokens by being endorsed), and
    ///         can automatically set operators in ERC-7540 vaults (e.g. the VaultRouter) is always an operator.
    function endorse(address user) external;

    /// @notice Removes the endorsed user
    function veto(address user) external;

    /// @notice Returns whether the user is endorsed
    /// @param user The address to check for endorsement status
    /// @return True if the user is endorsed, false otherwise
    function endorsed(address user) external view returns (bool);

    //----------------------------------------------------------------------------------------------
    // Pause management
    //----------------------------------------------------------------------------------------------

    /// @notice Pause any contracts that depend on `Root.paused()`
    function pause() external;

    /// @notice Unpause any contracts that depend on `Root.paused()`
    function unpause() external;

    //----------------------------------------------------------------------------------------------
    // Timelocked ward management
    //----------------------------------------------------------------------------------------------

    /// @notice Execute a scheduled rely
    /// @dev    Can be triggered by anyone since the scheduling is protected
    function executeScheduledRely(address target) external;

    //----------------------------------------------------------------------------------------------
    // External contract ward management
    //----------------------------------------------------------------------------------------------

    /// @notice Make an address a ward on any contract that Root is a ward on
    function relyContract(address target, address user) external;

    /// @notice Removes an address as a ward on any contract that Root is a ward on
    function denyContract(address target, address user) external;
}

src/core/messaging/interfaces/IAdapter.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @notice Cross-chain transport used by `MultiAdapter` to carry protocol payloads between chains.
/// @dev    Implementations MUST NOT revert in `send` or `estimate` for a route they are configured for.
///         `MultiAdapter` fans every outgoing payload out over the whole active adapter set and bubbles any
///         revert, and `Gateway` estimates before it dispatches, so one failing adapter vetoes all outbound
///         traffic of the pools that configure it, even when the remaining adapters would satisfy the
///         threshold on their own. Adapters placed after the failing one are never reached either, so a
///         `StandbyAdapter` does not get to record its send, and nothing is queued for later repayment since
///         the revert precedes the underpaid bookkeeping. Rotating away from such an adapter cannot go
///         through the hub, which would send over the same broken set: see {IMultiAdapter-setAdapters} for
///         the recovery runbook.
interface IAdapter {
    //----------------------------------------------------------------------------------------------
    // Errors
    //----------------------------------------------------------------------------------------------

    error NotEntrypoint();
    error UnknownChainId();

    //----------------------------------------------------------------------------------------------
    // Outgoing
    //----------------------------------------------------------------------------------------------

    /// @notice Send a payload to the destination chain
    /// @param centrifugeId The destination chain ID
    /// @param payload The message payload to send
    /// @param gasLimit The gas limit for execution on the destination chain
    /// @param refund The address to receive any excess payment refund
    /// @return adapterData Adapter-specific data returned from the send operation
    function send(uint16 centrifugeId, bytes calldata payload, uint256 gasLimit, address refund)
        external
        payable
        returns (bytes32 adapterData);

    /// @notice Estimate the total cost in native gas tokens
    /// @param centrifugeId The destination chain ID
    /// @param payload The message payload to send
    /// @param gasLimit The gas limit for execution on the destination chain
    /// @return The estimated cost in native gas tokens
    function estimate(uint16 centrifugeId, bytes calldata payload, uint256 gasLimit) external view returns (uint256);
}

src/core/messaging/interfaces/IAdapterEntrypoint.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {IMessageGas} from "./IMessageGas.sol";
import {IMessageHandler} from "./IMessageHandler.sol";

/// @notice Thin entrypoint that adapters use to reach the MultiAdapter. Extends {IMessageHandler} (the regular
///         vote-and-maybe-execute path) with the proof-adapter primitives {vote} and {execute}, which decouple
///         voting from execution. Adapters depend on this small interface instead of the full {IMultiAdapter}.
interface IAdapterEntrypoint is IMessageHandler {
    //----------------------------------------------------------------------------------------------
    // Errors
    //----------------------------------------------------------------------------------------------

    /// @notice Dispatched when {execute} is called for a payload whose votes have not reached the threshold
    ///         (i.e. some required adapter has not delivered its proof yet).
    error NotEnoughVotes();

    //----------------------------------------------------------------------------------------------
    // Incoming
    //----------------------------------------------------------------------------------------------

    /// @notice Records the calling adapter's vote for `payload` WITHOUT ever executing it, even once the
    ///         threshold is reached. Proof adapters call this on receipt; execution is deferred to {execute}.
    /// @dev    Unlike `handle()`, this never forwards to the gateway and never consumes votes, so a cheap proof
    ///         delivery can never trigger an under-funded inline execution.
    /// @param  centrifugeId Source chain identifier
    /// @param  payload The wrapped payload (session-id prefixed) to vote on
    function vote(uint16 centrifugeId, bytes calldata payload) external;

    /// @notice Executes a payload whose votes have already reached the threshold,
    ///         consuming the quorum's votes. Does NOT cast a vote of its own.
    /// @dev    Reverts with {NotEnoughVotes} if the threshold is not met.
    /// @param  centrifugeId Source chain identifier
    /// @param  payload The wrapped payload (session-id prefixed) to execute
    function execute(uint16 centrifugeId, bytes calldata payload) external;

    //----------------------------------------------------------------------------------------------
    // View methods
    //----------------------------------------------------------------------------------------------

    /// @notice Gas properties of the messages this carries. An adapter that prices its own receive path
    ///         reads the reference from here and casts to the interface that prices it, so replacing it
    ///         is a single file() and never an adapter redeploy.
    function messageGas() external view returns (IMessageGas);
}

src/core/messaging/interfaces/IGateway.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {IAdapter} from "./IAdapter.sol";
import {IMessageGas} from "./IMessageGas.sol";
import {IMessageHandler} from "./IMessageHandler.sol";
import {IProtocolPauser} from "./IProtocolPauser.sol";
import {IMessageProcessor} from "./IMessageProcessor.sol";

import {IRecoverable} from "../../../misc/interfaces/IRecoverable.sol";

import {PoolId} from "../../types/PoolId.sol";

// Max length for a supported message. Note that a batch can use several messages with this length.
uint256 constant MESSAGE_MAX_LENGTH = 1_000;

// Max length of an error that happens when processing a message.
uint16 constant ERR_MAX_LENGTH = 32 * 4; // enough for most errors

/// @notice Interface for dispatch-only gateway
interface IGateway is IMessageHandler, IRecoverable {
    //----------------------------------------------------------------------------------------------
    // Structs
    //----------------------------------------------------------------------------------------------

    struct Underpaid {
        uint128 gasLimit;
        uint64 counter;
    }

    //----------------------------------------------------------------------------------------------
    // Events
    //----------------------------------------------------------------------------------------------

    event File(bytes32 indexed what, address addr);
    event PrepareMessage(uint16 indexed centrifugeId, PoolId indexed poolId, bytes message);
    event UnderpaidBatch(uint16 indexed centrifugeId, bytes batch, bytes32 batchHash);
    event RepayBatch(uint16 indexed centrifugeId, bytes batch);
    event ExecuteMessage(uint16 indexed centrifugeId, bytes32 messageHash);
    event FailMessage(uint16 indexed centrifugeId, bytes32 messageHash, bytes error);
    event ClearFailedMessage(uint16 indexed centrifugeId, bytes32 messageHash);
    event UpdateManager(PoolId indexed poolId, address indexed who, bool canManage);

    //----------------------------------------------------------------------------------------------
    // Errors
    //----------------------------------------------------------------------------------------------

    /// @notice Dispatched when the `what` parameter of `file()` is not supported by the implementation.
    error FileUnrecognizedParam();

    /// @notice Dispatched when the batch is ended without starting it.
    error NoBatched();

    /// @notice Dispatched when the gateway is paused.
    error Paused();

    /// @notice Dispatched when the gateway tries to send an empty message.
    error EmptyMessage();

    /// @notice Dispatched when the message exceeds MESSAGE_MAX_LENGTH.
    error TooLongMessage();

    /// @notice Dispatched when a message that has not failed is retried.
    error NotFailedMessage();

    /// @notice Dispatched when a batch that has not been underpaid is repaid.
    error NotUnderpaidBatch();

    /// @notice Dispatched when the content of a batch doesn't belong to the same pool
    error MalformedBatch();

    /// @notice Dispatched when a message claims to originate from the local chain. A message reaching
    ///         `handle` always crossed a real inter-chain bridge (same-chain hub<->spoke calls bypass
    ///         Gateway entirely via a direct call), so this can only happen for a forged message.
    error CannotBeReceivedLocally();

    /// @notice Dispatched when a message arrives from a chain that is not its expected source.
    error SourceMismatch();

    /// @notice Dispatched when there is not enough gas to send the message
    error NotEnoughGas();

    /// @notice Dispatched when the batch requires more gas than the destination chain can execute in a single transaction
    error BatchTooExpensive();

    /// @notice Dispatched when a message was batched but there was a payment for it
    error NotPayable();

    /// @notice Dispatched when the callback fails with no error
    error CallFailedWithEmptyRevert();

    /// @notice Dispatched when the callback is called inside the callback
    error CallbackIsLocked();

    /// @notice Dispatched when the user doesn't call lockCallback()
    error CallbackWasNotLocked();

    /// @notice Dispatched when the callback was not from the sender
    error CallbackWasNotFromSender();

    /// @notice Dispatched when there is not enough msg.value to send to the callback
    error NotEnoughValueForCallback();

    /// @notice Dispatched when trying to create a batch during the send loop
    error ReentrantBatchCreation();

    //----------------------------------------------------------------------------------------------
    // Administration
    //----------------------------------------------------------------------------------------------

    /// @notice Used to update an address (state variable) on very rare occasions
    /// @param what The name of the variable to be updated
    /// @param data New address
    function file(bytes32 what, address data) external;

    /// @notice Allow/disallow an account to act as gateway manager for a pool.
    /// @dev    WARNING: Gateway managers carry very significant permissions. A manager can call
    ///         `Gateway.handle` directly with an arbitrary centrifugeId and raw message bytes,
    ///         which lets it forge any hub-originated message for its pool — including
    ///         `SetPoolAdapters`, `UpdateManager`, and `ManagerCallFromHub`. This is intentional for
    ///         recovery scenarios (e.g. replaying a valid message that the transport dropped), but
    ///         it means a compromised or malicious manager key is equivalent to hub-level authority
    ///         over that pool. Grant this role only to smart contracts that constrain what messages
    ///         can be injected; never grant it to a plain EOA.
    /// @param poolId The pool identifier
    /// @param who Address to grant or revoke the gateway manager role for
    /// @param canManage True to grant, false to revoke
    function updateManager(PoolId poolId, address who, bool canManage) external;

    /// @notice Remove a failed message so it can no longer be retried.
    /// @dev    Restricted to wards or a manager of the message's pool. Intended for messages that cannot
    ///         be retried successfully and should not persist in the failed queue. It is NOT a reliable
    ///         way to block a message that would currently execute: `retry` is permissionless, so anyone
    ///         can front-run the clear and force execution. Only clear messages that still revert on
    ///         retry. Decrements the failed count by one, mirroring `retry`'s per-instance semantics.
    /// @param centrifugeId The source chain the message originated from
    /// @param message The failed message to remove
    function clearFailedMessage(uint16 centrifugeId, bytes memory message) external;

    //----------------------------------------------------------------------------------------------
    // Message handling
    //----------------------------------------------------------------------------------------------

    /// @notice Repay an underpaid batch
    /// @param centrifugeId The destination chain
    /// @param batch The batch to repay
    /// @param refund Address to refund excess payment
    function repay(uint16 centrifugeId, bytes memory batch, address refund) external payable;

    /// @notice Retry a failed message
    /// @dev    Permissionless: anyone may re-execute a failed message once its failure cause is gone.
    /// @param centrifugeId The source chain the message originated from
    /// @param message The message to retry
    function retry(uint16 centrifugeId, bytes memory message) external;

    /// @notice Handling outgoing messages
    /// @param centrifugeId Destination chain
    /// @param message The message to send
    /// @param unpaidMode Tells if storing the message as unpaid if not enough funds
    /// @param refund Address to refund excess payment
    function send(uint16 centrifugeId, bytes calldata message, bool unpaidMode, address refund) external payable;

    //----------------------------------------------------------------------------------------------
    // Batching
    //----------------------------------------------------------------------------------------------

    /// @notice Automatic batching of cross-chain transactions through a callback.
    ///         Any cross-chain transactions triggered in this callback will automatically be batched.
    /// @dev    Should be used like:
    ///         ```
    ///         contract Integration {
    ///             IGateway gateway;
    ///
    ///             function doSomething(PoolId poolId) external {
    ///                 gateway.withBatch(abi.encodeWithSelector(Integration.callback.selector, poolId));
    ///             }
    ///
    ///             function callback(PoolId poolId) external {
    ///                 // Avoid reentrancy to the callback and ensure it's called from withBatch in the same contract:
    ///                 gateway.lockCallback();
    ///
    ///                 // Call several hub, balance sheet, or spoke methods that trigger cross-chain transactions
    ///             }
    ///         }
    ///         ```
    ///
    ///         NOTE: inside callback, `msgSender` should be used instead of msg.sender
    /// @param  callbackData encoding data for the callback method
    /// @param  callbackValue msg.value to send to the callback
    /// @param  refund Address to refund excess payment
    function withBatch(bytes memory callbackData, uint256 callbackValue, address refund) external payable;

    /// @notice Same as withBatch(..), but without sending any msg.value to the callback
    function withBatch(bytes memory callbackData, address refund) external payable;

    /// @notice Ensures the callback is called by withBatch in the same contract.
    /// @dev calling this at the very beginning inside the multicall means:
    ///         - The callback is called from the gateway under `withBatch`.
    ///         - The callback is called from the same contract, because withBatch uses `msg.sender` as target for the callback
    ///         - The callback that uses this can only be called once inside withBatch scope. No reentrancy.
    function lockCallback() external;

    //----------------------------------------------------------------------------------------------
    // View methods
    //----------------------------------------------------------------------------------------------

    /// @notice Protocol's internal chain identifier for this network, distinct from the EVM chain ID
    function localCentrifugeId() external view returns (uint16);

    /// @notice MultiAdapter used for outbound message dispatch and inbound quorum verification
    function adapter() external view returns (IAdapter);

    /// @notice Handler that routes confirmed inbound cross-chain messages to their target contracts, and the
    ///         sole authority on how a message is framed, routed and attributed to a source chain
    function processor() external view returns (IMessageProcessor);

    /// @notice Provides gas cost estimates for cross-chain messages
    function messageGas() external view returns (IMessageGas);

    /// @notice ProtocolGuardian that can pause/unpause all cross-chain messaging
    function pauser() external view returns (IProtocolPauser);

    /// @notice Returns whether `who` is a gateway manager for `poolId`.
    ///         See {updateManager} for the security implications of this role.
    function manager(PoolId poolId, address who) external view returns (bool);

    /// @notice Returns the underpaid batch info for a given chain and batch hash
    /// @param centrifugeId The destination chain identifier
    /// @param batchHash The hash of the underpaid batch
    /// @return gasLimit The gas limit for the batch
    /// @return counter The number of underpaid instances
    function underpaid(uint16 centrifugeId, bytes32 batchHash) external view returns (uint128 gasLimit, uint64 counter);

    /// @notice Returns the number of failed message instances for a given chain and message hash
    /// @param centrifugeId The source chain identifier
    /// @param messageHash The hash of the failed message
    /// @return The count of failed instances
    function failedMessages(uint16 centrifugeId, bytes32 messageHash) external view returns (uint256);

    /// @notice Returns the current gateway batching level
    /// @return Whether the gateway is currently batching
    function isBatching() external view returns (bool);
}

src/core/messaging/interfaces/IGatewayHandlers.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {D18} from "../../../misc/types/D18.sol";

import {PoolId} from "../../types/PoolId.sol";
import {AssetId} from "../../types/AssetId.sol";
import {ShareClassId} from "../../types/ShareClassId.sol";
import {IPolicy} from "../../utils/interfaces/IPolicy.sol";
import {VaultUpdateKind} from "../libraries/MessageLib.sol";
import {IRegistrar} from "../../spoke/interfaces/IRegistrar.sol";
import {ISpokeRequestManager} from "../../spoke/interfaces/ISpokeRequestManager.sol";

//--------------------------------------------------------------------------------------------------
// Hub Handlers
//--------------------------------------------------------------------------------------------------

/// @notice Interface for Hub methods called by messages
interface IHubGatewayHandler {
    /// @notice Tells that an asset was already registered in Vaults, in order to perform the corresponding register.
    function registerAsset(AssetId assetId, uint8 decimals) external;

    /// @notice Handles a request originating from the Spoke side.
    /// @param  poolId The pool id
    /// @param  scId The share class id
    /// @param  assetId The asset id
    /// @param  payload The request payload to be processed
    function request(PoolId poolId, ShareClassId scId, AssetId assetId, bytes calldata payload) external;

    /// @notice Update a holding by request from Vaults.
    /// @dev    The holding delta is valued at the hub-side valuation; the wire message's price field is
    ///         deprecated and ignored.
    function updateAssets(
        uint16 centrifugeId,
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        uint128 amount,
        bool isIncrease,
        bool isSnapshot,
        uint64 nonce
    ) external;

    /// @notice Forward an initiated share transfer to the destination chain.
    function initiateTransferShares(
        uint16 originCentrifugeId,
        uint16 targetCentrifugeId,
        PoolId poolId,
        ShareClassId scId,
        bytes32 sender,
        bytes32 receiver,
        uint128 amount,
        uint128 extraGasLimit,
        address refund
    ) external payable;

    /// @notice Updates the total issuance of shares by request from vaults.
    function updateShares(
        uint16 centrifugeId,
        PoolId poolId,
        ShareClassId scId,
        uint128 amount,
        bool isIssuance,
        bool isSnapshot,
        uint64 nonce
    ) external;
}

//--------------------------------------------------------------------------------------------------
// Spoke Handlers
//--------------------------------------------------------------------------------------------------

/// @notice Interface for spoke related methods called by messages
interface ISpokeGatewayHandler {
    /// @notice    New pool details from an existing Centrifuge pool are added.
    /// @param     poolId The pool id
    function addPool(PoolId poolId) external;

    /// @notice     New share class details from an existing Centrifuge pool are added.
    /// @param      salt Deterministic deployment salt, whose first 8 bytes MUST be `poolId`. Registrars are
    ///             shared across pools, so this keeps one pool out of another pool's salt namespace.
    /// @param      payload Opaque data forwarded to the registrar on token creation; empty if unused
    function addShareClass(
        PoolId poolId,
        ShareClassId scId,
        string memory tokenName,
        string memory tokenSymbol,
        uint8 decimals,
        bytes32 salt,
        IRegistrar registrar,
        bytes memory payload
    ) external;

    /// @notice Updates the request manager for a pool
    /// @param  poolId The centrifuge pool id
    /// @param  manager The new request manager address
    function setRequestManager(PoolId poolId, ISpokeRequestManager manager) external;

    /// @notice Install or replace the policy enforced on this pool's balance-sheet manager methods
    /// @param  poolId The pool id
    /// @param  policy The policy contract to install (address(0) to remove policy enforcement)
    function setPolicy(PoolId poolId, IPolicy policy) external;

    /// @notice Record a Hub-authorized, out-of-policy call in the local ledger (from a Hub {Authorize} message)
    /// @param  poolId The pool the authorized call targets
    /// @param  data The exact spoke calldata being authorized
    function authorize(PoolId poolId, bytes calldata data) external;

    /// @notice Revoke one outstanding authorization for `data` (from a Hub {Unauthorize} message)
    /// @param  poolId The pool the authorized call targets
    /// @param  data The exact spoke calldata whose authorization is revoked
    function unauthorize(PoolId poolId, bytes calldata data) external;

    /// @notice Grants or revokes the spoke pool manager role
    function updateManager(PoolId poolId, address who, bool canManage) external;

    /// @notice Grants or revokes the bridger role gating cross-chain share transfers
    function updateBridger(PoolId poolId, address who, bool canBridge) external;

    /// @notice   Updates the tokenName and tokenSymbol of a share class token
    function updateShareMetadata(PoolId poolId, ShareClassId scId, string memory tokenName, string memory tokenSymbol)
        external;

    /// @notice  Updates the price (pool currency amount per share class token) of a share class token
    /// @param  poolId The pool id
    /// @param  scId The share class id
    /// @param  price The price of pool currency per share class token.
    /// @param  computedAt The timestamp when the price was computed
    function updatePricePoolPerShare(PoolId poolId, ShareClassId scId, D18 price, uint64 computedAt) external;

    /// @notice  Updates the price (pool currency amount per asset unit) of an asset
    /// @param  poolId The pool id
    /// @param  scId The share class id
    /// @param  assetId The asset id
    /// @param  price The price of pool currency per asset unit.
    /// @param  computedAt The timestamp when the price was computed
    function updatePricePoolPerAsset(PoolId poolId, ShareClassId scId, AssetId assetId, D18 price, uint64 computedAt)
        external;

    /// @notice Updates the hook of a share class token
    /// @notice Updates the restrictions on a share class token for a specific user
    /// @param  poolId The centrifuge pool id
    /// @param  scId The share class id
    /// @param  update The restriction update in the form of a bytes array indicating
    ///                the restriction to be updated, the user to be updated, and a validUntil timestamp.
    function updateRestriction(PoolId poolId, ShareClassId scId, bytes memory update) external;

    /// @notice Mints share class tokens to a recipient
    function executeTransferShares(PoolId poolId, ShareClassId scId, bytes32 receiver, uint128 amount) external;

    /// @notice Handles a request callback originating from the Hub side.
    /// @dev    Results from a Spoke-to-Hub-request as second order callback from the Hub.
    /// @param  poolId The pool id
    /// @param  scId The share class id
    /// @param  assetId The asset id
    /// @param  payload The payload to be processed by the request callback
    function requestCallback(PoolId poolId, ShareClassId scId, AssetId assetId, bytes memory payload) external;

    /// @notice Updates a vault based on VaultUpdateKind
    /// @param  poolId The centrifuge pool id
    /// @param  scId The share class id
    /// @param  assetId The asset id
    /// @param  vaultOrFactory The address of the vault or the factory, depending on the kind value
    /// @param  kind The kind of action applied
    /// @param  payload Opaque data forwarded to the factory on DeployAndLink; empty otherwise
    function updateVault(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        address vaultOrFactory,
        VaultUpdateKind kind,
        bytes calldata payload
    ) external;
}

src/core/messaging/interfaces/IGatewaySenders.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {D18} from "../../../misc/types/D18.sol";

import {PoolId} from "../../types/PoolId.sol";
import {AssetId} from "../../types/AssetId.sol";
import {ShareClassId} from "../../types/ShareClassId.sol";
import {VaultUpdateKind, ManagerKind} from "../libraries/MessageLib.sol";

/// @notice Share class metadata carried by the NotifyShareClass message, bundled to keep the sender signature
///         (and its callers' stack) within limits.
struct ShareClassMetadata {
    string name;
    string symbol;
    uint8 decimals;
}

interface ILocalCentrifugeId {
    error CannotBeSentLocally();

    function localCentrifugeId() external view returns (uint16);
}

/// @notice Interface for dispatch-only gateway
interface IScheduleAuthMessageSender is ILocalCentrifugeId {
    /// @notice Creates and send the message
    function sendScheduleUpgrade(uint16 centrifugeId, bytes32 target, address refund) external payable;

    /// @notice Creates and send the message
    function sendCancelUpgrade(uint16 centrifugeId, bytes32 target, address refund) external payable;
}

/// @notice Interface for dispatch-only gateway
interface IHubMessageSender is ILocalCentrifugeId {
    /// @notice Creates and send the message
    function sendNotifyPool(uint16 centrifugeId, PoolId poolId, address refund) external payable;

    /// @notice Creates and send the message
    function sendNotifyShareClass(
        uint16 centrifugeId,
        PoolId poolId,
        ShareClassId scId,
        ShareClassMetadata memory metadata,
        bytes32 salt,
        bytes32 registrar,
        bytes calldata payload,
        uint128 extraGasLimit,
        address refund
    ) external payable;

    /// @notice Creates and send the message
    function sendNotifyShareMetadata(
        uint16 centrifugeId,
        PoolId poolId,
        ShareClassId scId,
        string memory name,
        string memory symbol,
        uint128 extraGasLimit,
        address refund
    ) external payable;

    /// @notice Creates and send the message
    function sendNotifyPricePoolPerShare(
        uint16 centrifugeId,
        PoolId poolId,
        ShareClassId scId,
        D18 pricePoolPerShare,
        uint64 computedAt,
        address refund
    ) external payable;

    /// @notice Creates and send the message
    function sendNotifyPricePoolPerAsset(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        D18 pricePoolPerAsset,
        address refund
    ) external payable;

    /// @notice Creates and send the message
    function sendUpdateRestriction(
        uint16 centrifugeId,
        PoolId poolId,
        ShareClassId scId,
        bytes calldata payload,
        uint128 extraGasLimit,
        address refund
    ) external payable;

    /// @notice Routes a manager call to its target. Local: through the `Envoy`, forwarding `value`. Remote:
    ///         emits a `ManagerCallFromHub` message delivered on the destination chain via its `Envoy`.
    /// @dev    `Hub.managerCall` enforces `value == msgValue()` locally / `value == 0` remotely. `extraGasLimit`
    ///         meters the remote delivery (inert on the local branch).
    function sendManagerCallFromHub(
        uint16 centrifugeId,
        PoolId poolId,
        address target,
        bytes calldata payload,
        uint128 extraGasLimit,
        uint256 value,
        address refund
    ) external payable;

    /// @notice Creates and send the message
    function sendUpdateVault(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        bytes32 vaultOrFactory,
        VaultUpdateKind kind,
        bytes calldata payload,
        uint128 extraGasLimit,
        address refund
    ) external payable;

    /// @notice Creates and send the message
    function sendSetRequestManager(uint16 centrifugeId, PoolId poolId, bytes32 manager, address refund) external payable;

    /// @notice Creates and send the message
    function sendSetPolicy(uint16 centrifugeId, PoolId poolId, bytes32 policy, address refund) external payable;

    /// @notice Creates and send the message
    function sendAuthorizeSpokeCall(uint16 centrifugeId, PoolId poolId, bytes calldata data, address refund)
        external
        payable;

    /// @notice Creates and send the message
    function sendUnauthorizeSpokeCall(uint16 centrifugeId, PoolId poolId, bytes calldata data, address refund)
        external
        payable;

    /// @notice Creates and send the message
    function sendUpdateManager(
        uint16 centrifugeId,
        PoolId poolId,
        ManagerKind kind,
        bytes32 who,
        bool canManage,
        address refund
    ) external payable;

    /// @notice Creates and send the message
    function sendExecuteTransferShares(
        uint16 originCentrifugeId,
        uint16 targetCentrifugeId,
        PoolId poolId,
        ShareClassId scId,
        bytes32 receiver,
        uint128 amount,
        uint128 extraGasLimit,
        address refund
    ) external payable;

    /// @notice Creates and send the message
    function sendRequestCallback(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        bytes calldata payload,
        uint128 extraGasLimit,
        bool unpaidMode,
        address refund
    ) external payable;

    /// @notice Creates and send the message
    function sendSetPoolAdapters(
        uint16 centrifugeId,
        PoolId poolId,
        bytes32[] memory adapters,
        uint8 threshold,
        uint16 targetSessionId,
        address refund
    ) external payable;
}

/// @notice Interface for dispatch-only gateway
interface ISpokeMessageSender is ILocalCentrifugeId {
    struct UpdateData {
        uint128 netAmount;
        bool isIncrease;
        bool isSnapshot;
        uint64 nonce;
    }

    /// @notice Creates and send the message
    function sendInitiateTransferShares(
        uint16 centrifugeId,
        PoolId poolId,
        ShareClassId scId,
        bytes32 sender,
        bytes32 receiver,
        uint128 amount,
        uint128 extraGasLimit,
        uint128 remoteExtraGasLimit,
        address refund
    ) external payable;

    /// @notice Creates and send the message
    function sendRegisterAsset(uint16 centrifugeId, AssetId assetId, uint8 decimals, address refund) external payable;

    /// @notice Creates and send the message
    /// @dev    The message carries no price; the hub values the delta at its own valuation.
    function sendUpdateAssets(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        UpdateData calldata data,
        uint128 extraGasLimit,
        address refund
    ) external payable;

    /// @notice Creates and send the message
    /// @dev    ABI-compatibility overload of `sendUpdateAssets` for the deployed v3.1.0 BalanceSheet; the price
    ///         is ignored (the hub values the delta at its own valuation).
    function sendUpdateHoldingAmount(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        UpdateData calldata data,
        D18 pricePoolPerAsset,
        uint128 extraGasLimit,
        address refund
    ) external payable;

    /// @notice Creates and send the message
    function sendUpdateShares(
        PoolId poolId,
        ShareClassId scId,
        UpdateData calldata data,
        uint128 extraGasLimit,
        address refund
    ) external payable;

    /// @notice Creates and send the message
    function sendRequest(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        bytes calldata payload,
        uint128 extraGasLimit,
        bool unpaidMode,
        address refund
    ) external payable;

    /// @notice Creates and sends a ManagerCallFromSpoke message, routed on the destination to the target's
    ///         `IManagerCallFromSpoke.fromSpoke` via the Envoy. The target validates `(centrifugeId, sender)`.
    /// @param poolId The pool identifier
    /// @param target The destination target contract (as bytes32)
    /// @param payload The action payload (any scId is encoded here)
    /// @param sender The spoke-side initiator (as bytes32)
    /// @param extraGasLimit Additional gas for cross-chain execution
    /// @param refund Address to refund excess payment
    function sendManagerCallFromSpoke(
        PoolId poolId,
        bytes32 target,
        bytes calldata payload,
        bytes32 sender,
        uint128 extraGasLimit,
        address refund
    ) external payable;
}

src/core/messaging/interfaces/IMessageGas.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @notice Defines the gas properties of raw messages.
/// @dev    Values only: how a message is framed or attributed is `IMessageParser`, which is read from the
///         processor instead, so that filing this interface cannot alter source-chain authentication.
interface IMessageGas {
    /// @notice Gas limit for the execution cost of an individual message in a remote chain from the adapter.
    /// @dev    NOTE: In the future we could want to dispatch:
    ///         - by destination chain (for non-EVM chains)
    ///         - by message type
    ///         - by inspecting the payload checking different subsmessages that alter the endpoint processing
    /// @param centrifugeId Where to the cost is defined
    /// @param message Individual message
    /// @return Estimated cost in WEI units
    function messageOverallGasLimit(uint16 centrifugeId, bytes calldata message) external view returns (uint128);

    /// @notice Similar to messageOverallGasLimit but taking only into account the exact gas to process it from the Gateway
    ///         for processing the message without any extra addition
    function messageProcessingGasLimit(uint16 centrifugeId, bytes calldata message) external view returns (uint128);

    /// @notice Maximum Gas limit for a batch, determined how much the destination chain can process
    /// @param centrifugeId Destination where to the maximum cost is defined
    function maxBatchGasLimit(uint16 centrifugeId) external view returns (uint128);

    /// @notice Gas reserved in every message budget to handle a worst-case processor revert.
    function messageFailureGasReserve() external view returns (uint128);
}

src/core/messaging/interfaces/IMessageHandler.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @notice Generic interface for entities that handle incoming messages
interface IMessageHandler {
    //----------------------------------------------------------------------------------------------
    // Incoming
    //----------------------------------------------------------------------------------------------

    /// @notice Handling incoming messages
    /// @param centrifugeId Source chain
    /// @param message Incoming message
    function handle(uint16 centrifugeId, bytes calldata message) external;
}

src/core/messaging/interfaces/IMessageParser.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {PoolId} from "../../types/PoolId.sol";

/// @notice Defines how a raw message is framed, routed and attributed to a source chain.
/// @dev    Deliberately separate from `IMessageGas`: these answers authenticate a message, so they are
///         read from the processor that deserializes it (a Root-filed dependency) rather than from the
///         ops-filed gas service. Splitting them also makes the two views structurally unable to disagree.
interface IMessageParser {
    /// @notice Inspect the message to return the length
    function messageLength(bytes calldata message) external pure returns (uint16);

    /// @notice Inspect the message to return the associated PoolId if any
    function messagePoolId(bytes calldata message) external pure returns (PoolId);

    /// @notice The pool whose adapter set should route/verify the message. Same as `messagePoolId`, except a
    ///         SetPoolAdapters for a pool with no adapter set yet (`poolConfigured == false`) falls back to
    ///         the global pool, so the pool's first adapter configuration can be delivered over the global set.
    function routePoolId(bytes calldata message, bool poolConfigured) external pure returns (PoolId);

    /// @notice Returns the centrifugeId that `message` must originate from, or 0 if any source is permitted.
    function messageSourceCentrifugeId(bytes calldata message) external pure returns (uint16);
}

src/core/messaging/interfaces/IMessageProcessor.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {IGateway} from "./IGateway.sol";
import {IMultiAdapter} from "./IMultiAdapter.sol";
import {IScheduleAuth} from "./IScheduleAuth.sol";
import {IMessageParser} from "./IMessageParser.sol";
import {IMessageHandler} from "./IMessageHandler.sol";
import {ISpokeGatewayHandler, IHubGatewayHandler} from "./IGatewayHandlers.sol";

interface IMessageProcessor is IMessageHandler, IMessageParser {
    //----------------------------------------------------------------------------------------------
    // Events
    //----------------------------------------------------------------------------------------------

    event File(bytes32 indexed what, address addr);

    //----------------------------------------------------------------------------------------------
    // Errors
    //----------------------------------------------------------------------------------------------

    /// @notice Dispatched when the `what` parameter of `file()` is not supported by the implementation.
    error FileUnrecognizedParam();

    /// @notice Dispatched when an invalid message is trying to handle
    error InvalidMessage(uint8 code);

    /// @notice Dispatched when the manager kind in an `UpdateManager` message is not supported
    error InvalidManagerKind();

    //----------------------------------------------------------------------------------------------
    // View methods
    //----------------------------------------------------------------------------------------------

    /// @notice Routes and batches cross-chain messages between hub and spoke
    function gateway() external view returns (IGateway);

    /// @notice Handles multi-protocol message verification and routing for cross-chain communication
    function multiAdapter() external view returns (IMultiAdapter);

    /// @notice Processes administrative cross-chain messages for pool, share class, and vault operations
    function spokeHandler() external view returns (ISpokeGatewayHandler);

    /// @notice Hub-side handler for investment request processing and share issuance
    function hubHandler() external view returns (IHubGatewayHandler);

    /// @notice Processes timelocked rely/deny operations received from remote chains
    function scheduleAuth() external view returns (IScheduleAuth);

    //----------------------------------------------------------------------------------------------
    // Administration
    //----------------------------------------------------------------------------------------------

    /// @notice Updates a contract parameter
    /// @param what Name of the parameter to update
    ///         (accepts 'hubHandler', 'gateway', 'spokeHandler', 'multiAdapter', 'envoy')
    /// @param data New value given to the `what` parameter
    function file(bytes32 what, address data) external;
}

src/core/messaging/interfaces/IMultiAdapter.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {IAdapter} from "./IAdapter.sol";
import {IMessageParser} from "./IMessageParser.sol";
import {IMessageHandler} from "./IMessageHandler.sol";
import {IAdapterEntrypoint} from "./IAdapterEntrypoint.sol";

import {PoolId} from "../../types/PoolId.sol";

uint8 constant MAX_ADAPTER_COUNT = 8;

/// @notice Interface for handling several adapters transparently
interface IMultiAdapter is IAdapter, IAdapterEntrypoint {
    //----------------------------------------------------------------------------------------------
    // Structs
    //----------------------------------------------------------------------------------------------

    /// @dev Each adapter struct is packed with the quorum and threshold to reduce SLOADs on handle
    struct Adapter {
        /// @notice Starts at 1 and maps to id - 1 as the index on the adapters array
        uint8 id;
        /// @notice Number of configured adapters
        uint8 quorum;
        /// @notice Number of votes required for a message to be executed. Less-equal to quorum
        uint8 threshold;
    }

    struct Adapters {
        /// @notice Session id of the currently active adapter set
        uint16 sessionId;
        /// @notice List of currently active adapters
        IAdapter[] list;
    }

    /// @dev Stash holding a blocked session's configuration so it can be restored on unblock.
    ///      A session is blocked iff its stashed list is non-empty.
    struct BlockedSession {
        uint8 threshold;
        bool wasActive;
        IAdapter[] list;
    }

    //----------------------------------------------------------------------------------------------
    // Events
    //----------------------------------------------------------------------------------------------

    event File(bytes32 indexed what, address addr);
    event SetAdapters(
        uint16 centrifugeId, PoolId indexed poolId, uint16 sessionId, IAdapter[] adapters, uint8 threshold
    );
    event BlockSession(uint16 centrifugeId, PoolId indexed poolId, uint16 sessionId);
    event UnblockSession(uint16 centrifugeId, PoolId indexed poolId, uint16 sessionId);
    event Vote(uint16 indexed centrifugeId, bytes32 indexed payloadId, bytes payload, IAdapter adapter);
    event Execute(uint16 indexed centrifugeId, bytes32 indexed payloadId, bytes payload, IAdapter adapter);
    event SendPayload(
        uint16 indexed centrifugeId,
        bytes32 indexed payloadId,
        bytes payload,
        IAdapter adapter,
        bytes32 adapterData,
        uint256 gasLimit,
        uint256 gasPaid,
        address refund
    );
    event UpdateManager(PoolId indexed poolId, address indexed who, bool canManage);

    //----------------------------------------------------------------------------------------------
    // Errors
    //----------------------------------------------------------------------------------------------

    /// @notice Dispatched when the `what` parameter of `file()` is not supported by the implementation.
    error FileUnrecognizedParam();

    /// @notice Dispatched when the contract is configured with an empty adapter set.
    error EmptyAdapterSet();

    /// @notice Dispatched when the threshold number is higher than the number of configured adapters (aka quorum).
    error ThresholdHigherThanQuorum();

    /// @notice Dispatched when the threshold is zero while adapters are configured, which would let any
    ///         single adapter forward payloads without consensus.
    error ZeroThreshold();

    /// @notice Dispatched when the provided `targetSessionId` does not equal the pool's next session id, so a
    ///         reordered, stale or reentrant configuration cannot desync the two endpoints under the same id.
    error UnexpectedSessionId();

    /// @notice Dispatched when the contract is configured with a number of adapter exceeding the maximum.
    error ExceedsMax();

    /// @notice Dispatched when the contract is configured with duplicate adapters.
    error NoDuplicatesAllowed();

    /// @notice Dispatched when the contract tries to handle a message from an adapter not contained in the adapter set.
    error InvalidAdapter();

    /// @notice Dispatched when trying to block a session that has no adapters configured.
    error SessionNotConfigured();

    /// @notice Dispatched when trying to unblock a session that is not currently blocked.
    error SessionNotBlocked();

    //----------------------------------------------------------------------------------------------
    // Administration
    //----------------------------------------------------------------------------------------------

    /// @notice Used to update an address (state variable) on very rare occasions
    /// @param what The name of the variable to be updated
    /// @param data New address
    function file(bytes32 what, address data) external;

    /// @notice Configure new adapters for a determined pool.
    /// @dev    Bumps the pool's local sessionId to `targetSessionId`, which must equal the pool's next session id
    ///         (current + 1), reverting otherwise. The normal path (`Hub.setAdapters`) derives that id once and
    ///         uses it for both endpoints, so the remote bumps its session in lockstep; a reordered, stale or
    ///         reentrant configuration fails closed. A manager calling this directly (a low-level recovery path,
    ///         e.g. `AdapterFailover`) passes its own next session id and is responsible for ensuring the
    ///         resulting sessionId matches the other endpoint, otherwise messages wrapped with the new session
    ///         won't verify.
    ///
    ///         Recovery runbook when an adapter of the active set starts reverting on `estimate`/`send`. Such an
    ///         adapter vetoes every outbound message of the pool, including the rotation itself, so `Hub.setAdapters`
    ///         and `Hub.updateManager` are unusable: both travel over the broken set before it can be replaced.
    ///         1. Identify the culprit: `activeAdapters()` returns the live set and its session id, and simulating
    ///            `estimate` per adapter isolates which one reverts.
    ///         2. Rotate the sending chain locally: a pool adapter manager calls this function directly, passing
    ///            `nextActiveSessionId()`. `AdapterFailover` is the intended wrapper, gating the rotation behind a
    ///            steward and a hub-vetoable timelock. Appoint that manager while the adapters are still healthy;
    ///            once the set is broken, a chain without one can only be reached by a Root spell on that chain.
    ///         3. Install the mirrored set on the other endpoint the same way. Each call only advances the session
    ///            counter of the chain it runs on, so from aligned endpoints one rotation per side keeps them aligned.
    ///         4. Verify that alignment before resuming traffic: `activeSessionId(remoteId, poolId)` here must equal
    ///            `activeSessionId(localCentrifugeId, poolId)` there. If a side lagged, call this function again on it
    ///            with the same set until the ids match, since a payload wrapped with a session id the receiver never
    ///            configured is rejected with {InvalidAdapter}.
    ///         5. Retire the superseded session with `blockSession()` on each receiving side, once the messages sent
    ///            under it have been delivered, following the flow documented in {IHub-setAdapters}.
    ///         6. Re-issue the operations that reverted during the outage: they were never queued, so there is no
    ///            underpaid backlog to repay.
    /// @param  centrifugeId Chain where the adapters are associated to.
    /// @param  poolId PoolId associated to the adapters
    /// @param  adapters New adapter addresses already deployed.
    ///         If the array is empty, it disables the usage for messages of that pool.
    /// @param  threshold Minimum number of adapters required to process the messages.
    ///         Must be at least 1 when `adapters` is non-empty; set `adapters.length` for full consensus.
    /// @param  targetSessionId The session id to install; must equal the pool's next session id (current + 1)
    function setAdapters(
        uint16 centrifugeId,
        PoolId poolId,
        IAdapter[] calldata adapters,
        uint8 threshold,
        uint16 targetSessionId
    ) external;

    /// @notice Mark a session as blocked, preventing its adapters from voting on incoming messages and, if it is the
    ///         active session, from sending outgoing messages. The session can later be recovered with unblockSession().
    /// @param  centrifugeId Chain where the adapters are configured for
    /// @param  poolId PoolId associated to the adapters
    /// @param  sessionId Session to block
    function blockSession(uint16 centrifugeId, PoolId poolId, uint16 sessionId) external;

    /// @notice Recover a previously blocked session, re-enabling its adapters.
    /// @param  centrifugeId Chain where the adapters are configured for
    /// @param  poolId PoolId associated to the adapters
    /// @param  sessionId Session to unblock
    function unblockSession(uint16 centrifugeId, PoolId poolId, uint16 sessionId) external;

    /// @notice Configures a manager address for a pool
    /// @dev    WARNING: a manager carries very significant permissions equivalent to controlling every
    ///         adapter configured for the pool. It can call `handle`/`vote`/`execute` on behalf of any
    ///         configured adapter address, and by doing so once per adapter can single-handedly reach
    ///         quorum and forward an arbitrary payload to the gateway as if real cross-chain consensus
    ///         had been reached — bypassing the M-of-N adapter security model entirely for that pool.
    ///         Grant this role only to smart contracts that constrain what can be submitted; never grant
    ///         it to a plain EOA. Mirrors the same trust level as `IGateway.updateManager`.
    /// @param poolId PoolId associated to the adapters
    /// @param who Manager address
    /// @param canManage If enabled as manager
    function updateManager(PoolId poolId, address who, bool canManage) external;

    //----------------------------------------------------------------------------------------------
    // Incoming
    //----------------------------------------------------------------------------------------------

    /// @notice Manager-driven variant of {IMessageHandler-handle}. Adapters submit via the two-argument
    ///         `handle`, identifying themselves through `msg.sender`. Here a manager of the payload's
    ///         pool submits on behalf of `adapter`, naming which configured adapter the message
    ///         belongs to. Equivalent to a vote followed by a possible execute.
    /// @param  centrifugeId Source chain identifier
    /// @param  payload The wrapped payload (session-id prefixed)
    /// @param  adapter The configured adapter the message is attributed to
    function handle(uint16 centrifugeId, bytes calldata payload, IAdapter adapter) external;

    /// @notice Manager-driven variant of {IAdapterEntrypoint-vote}. A manager of the payload's
    ///         pool casts a vote on behalf of `adapter` without ever executing it.
    /// @param  centrifugeId Source chain identifier
    /// @param  payload The wrapped payload (session-id prefixed)
    /// @param  adapter The configured adapter the vote is attributed to
    function vote(uint16 centrifugeId, bytes calldata payload, IAdapter adapter) external;

    /// @notice Manager-driven variant of {IAdapterEntrypoint-execute}. A manager of the payload's
    ///         pool executes an already-threshold-reached payload, attributing it to `adapter`. Reverts with
    ///         {NotEnoughVotes} if the threshold is not met. `adapter` only identifies the session config and
    ///         the {Execute} attribution; no vote of its own is cast.
    /// @param  centrifugeId Source chain identifier
    /// @param  payload The wrapped payload (session-id prefixed)
    /// @param  adapter A configured adapter the execution is attributed to
    function execute(uint16 centrifugeId, bytes calldata payload, IAdapter adapter) external;

    //----------------------------------------------------------------------------------------------
    // View methods
    //----------------------------------------------------------------------------------------------

    /// @notice Protocol's internal chain identifier for this network, distinct from the EVM chain ID
    function localCentrifugeId() external view returns (uint16);

    /// @notice Gateway that receives confirmed messages once adapter quorum is reached
    function gateway() external view returns (IMessageHandler);

    /// @notice Determines how a message is framed and which pool's adapter set carries it
    function parser() external view returns (IMessageParser);

    /// @notice Returns whether an address is a manager for a given pool
    /// @param poolId The pool to check
    /// @param who The address to check
    function manager(PoolId poolId, address who) external view returns (bool);

    /// @notice Returns the currently active session id for a given chain and pool
    /// @dev Monotonic and uint16, so a (chain, pool) pair supports 65,535 rotations and then `setAdapters`
    ///      reverts on the overflow for good: nothing decrements it and no auth path resets it, so that
    ///      pair's set can no longer be changed, by a manager or by Root
    /// @param centrifugeId The source chain identifier
    /// @param poolId The pool identifier
    function activeSessionId(uint16 centrifugeId, PoolId poolId) external view returns (uint16);

    /// @notice Returns the next session id to install for a given chain and pool (current + 1).
    ///         Callers are expected to pass this as the `targetSessionId` to {setAdapters}.
    /// @param centrifugeId The source chain identifier
    /// @param poolId The pool identifier
    function nextActiveSessionId(uint16 centrifugeId, PoolId poolId) external view returns (uint16);

    /// @notice Returns whether a session has been blocked
    /// @param centrifugeId The source chain identifier
    /// @param poolId The pool identifier
    /// @param sessionId The session identifier
    function blockedSession(uint16 centrifugeId, PoolId poolId, uint16 sessionId) external view returns (bool);

    /// @notice Returns the adapter at a given index for a specific session
    /// @param centrifugeId The source chain identifier
    /// @param poolId The pool identifier
    /// @param sessionId The session identifier
    /// @param index The index in the adapter array
    function adapters(uint16 centrifugeId, PoolId poolId, uint16 sessionId, uint256 index)
        external
        view
        returns (IAdapter);

    /// @notice Number of total configured adapters for a pool
    /// @param centrifugeId Chain where the adapter is configured for
    /// @param poolId PoolId associated to the adapters
    /// @return Needed amount
    function quorum(uint16 centrifugeId, PoolId poolId) external view returns (uint8);

    /// @notice Number of required votes to consider a message valid for processing
    /// @dev It's lower-equal than quorum
    /// @param centrifugeId Chain where the adapter is configured for
    /// @param poolId PoolId associated to the adapters
    /// @return Needed amount
    function threshold(uint16 centrifugeId, PoolId poolId) external view returns (uint8);

    /// @notice Counts how many times each incoming messages has been received per adapter.
    /// @dev    It supports parallel messages ( duplicates ). That means that the incoming messages could be
    ///         the result of two or more independent request from the user of the same type.
    ///         i.e. Same user would like to deposit same underlying asset with the same amount more then once.
    /// @param  centrifugeId Chain where the adapter is configured for
    /// @param  voteKey The vote-tally key: `keccak256(abi.encodePacked(routedPoolId, wrappedPayload))`, so a
    ///         global-set vote and a pool-set vote on the same bytes land in separate slots.
    /// @return The votes array
    function votes(uint16 centrifugeId, bytes32 voteKey) external view returns (int16[MAX_ADAPTER_COUNT] memory);

    /// @notice Returns the active adapter set for a pool
    /// @param centrifugeId Chain where the adapters are configured for
    /// @param poolId PoolId associated to the adapters
    /// @return The adapters list and last session id
    function activeAdapters(uint16 centrifugeId, PoolId poolId) external view returns (Adapters memory);
}

src/core/messaging/interfaces/IProtocolPauser.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

interface IProtocolPauser {
    event Pause();
    event Unpause();

    /// @notice Returns whether the root is paused
    /// @return True if the protocol is paused, false otherwise
    function paused() external view returns (bool);
}

src/core/messaging/interfaces/IScheduleAuth.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

interface IScheduleAuth {
    event ScheduleRely(address indexed target, uint256 indexed scheduledTime);
    event CancelRely(address indexed target);

    /// @notice Schedule relying a new ward after the delay has passed
    /// @param target The address to schedule as a ward
    function scheduleRely(address target) external;

    /// @notice Cancel a pending scheduled rely
    /// @param target The address to cancel the scheduled rely for
    function cancelRely(address target) external;
}

src/core/messaging/libraries/MessageLib.sol

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

import {CastLib} from "../../../misc/libraries/CastLib.sol";
import {MathLib} from "../../../misc/libraries/MathLib.sol";
import {BytesLib} from "../../../misc/libraries/BytesLib.sol";

import {PoolId} from "../../types/PoolId.sol";
import {AssetId} from "../../types/AssetId.sol";

enum MessageType {
    /// @dev Placeholder for null message type
    _Invalid,
    // --- Protocol-wide (pool-independent) ---
    // NOTE: everything below `NotifyPool` is treated as pool-dependent (carries its PoolId at offset 1);
    // see `messagePoolId` / `messageSourceCentrifugeId`. Keep pool-independent messages above `NotifyPool`.
    ScheduleUpgrade,
    CancelUpgrade,
    RegisterAsset,
    SetPoolAdapters,
    // --- Pool & share-class notifications ---
    NotifyPool,
    NotifyShareClass,
    NotifyPricePoolPerShare,
    NotifyPricePoolPerAsset,
    NotifyShareMetadata,
    // --- Share transfers ---
    InitiateTransferShares,
    ExecuteTransferShares,
    // --- Vaults & restrictions ---
    UpdateRestriction,
    UpdateVault,
    // --- Balance sheet ---
    UpdateAssets,
    UpdateShares,
    // --- Investment requests ---
    Request,
    RequestCallback,
    SetRequestManager,
    // --- Manager calls & authorization ---
    ManagerCallFromSpoke,
    ManagerCallFromHub,
    UpdateManager,
    SetPolicy,
    AuthorizeSpokeCall,
    UnauthorizeSpokeCall
}

/// @dev Used internally in the UpdateVault message (not represent a submessage)
enum VaultUpdateKind {
    DeployAndLink,
    Link,
    Unlink
}

/// @dev Used internally in the UpdateManager message to select which contract's manager is updated.
enum ManagerKind {
    Adapter,
    Gateway,
    Spoke,
    Bridger
}

library MessageLib {
    using MessageLib for bytes;
    using BytesLib for bytes;
    using CastLib for *;
    using MathLib for *;

    error UnknownMessageType();
    error InvalidPoolHome();
    error InvalidAssetHome();

    uint16 internal constant MAINNET_CENTRIFUGE_ID = 1;

    /// @dev Encode all message lengths in this constant to avoid a large list of if/elseif checks
    /// and reduce generated bytecode.
    /// If the message has some dynamic part, will be added later in `messageLength()`.
    // forgefmt: disable-next-item
    uint256 constant MESSAGE_LENGTHS_1 =
        (33  << uint8(MessageType.ScheduleUpgrade) * 8) +
        (33  << uint8(MessageType.CancelUpgrade) * 8) +
        (18  << uint8(MessageType.RegisterAsset) * 8) +
        (14  << uint8(MessageType.SetPoolAdapters) * 8) +
        (9   << uint8(MessageType.NotifyPool) * 8) +
        (250 << uint8(MessageType.NotifyShareClass) * 8) +
        (49  << uint8(MessageType.NotifyPricePoolPerShare) * 8) +
        (65  << uint8(MessageType.NotifyPricePoolPerAsset) * 8) +
        (185 << uint8(MessageType.NotifyShareMetadata) * 8) +
        (139  << uint8(MessageType.InitiateTransferShares) * 8) +
        (89  << uint8(MessageType.ExecuteTransferShares) * 8) +
        (41  << uint8(MessageType.UpdateRestriction) * 8) +
        (90  << uint8(MessageType.UpdateVault) * 8) +
        (91  << uint8(MessageType.UpdateAssets) * 8) +
        (75  << uint8(MessageType.UpdateShares) * 8) +
        (57  << uint8(MessageType.Request) * 8) +
        (57  << uint8(MessageType.RequestCallback) * 8) +
        (41  << uint8(MessageType.SetRequestManager) * 8) +
        (89  << uint8(MessageType.ManagerCallFromSpoke) * 8) +
        (43  << uint8(MessageType.UpdateManager) * 8) +
        (57  << uint8(MessageType.ManagerCallFromHub) * 8) +
        (41  << uint8(MessageType.SetPolicy) * 8) +
        (9   << uint8(MessageType.AuthorizeSpokeCall) * 8) +
        (9   << uint8(MessageType.UnauthorizeSpokeCall) * 8);

    function messageType(bytes memory message) internal pure returns (MessageType) {
        return MessageType(message.toUint8(0));
    }

    function messageCode(bytes memory message) internal pure returns (uint8) {
        return message.toUint8(0);
    }

    function messageLength(bytes memory message) internal pure returns (uint16 length) {
        uint8 kind = message.toUint8(0);
        require(kind != uint8(MessageType._Invalid) && kind <= uint8(type(MessageType).max), UnknownMessageType());

        length = uint16(uint8(bytes32(MESSAGE_LENGTHS_1)[31 - kind]));

        // NotifyShareClass carries a fixed 16-byte extraGasLimit suffix but its base length (250) leaves no
        // room for it within the single-byte table slot, so add it here. NotifyShareMetadata is kept uniform.
        if (kind == uint8(MessageType.NotifyShareClass) || kind == uint8(MessageType.NotifyShareMetadata)) {
            length += 16;
        }

        // Special treatment for messages with dynamic size:
        if (kind == uint8(MessageType.NotifyShareClass)) {
            length += 2 + message.toUint16(length); //payloadLength
        } else if (kind == uint8(MessageType.UpdateRestriction)) {
            length += 2 + message.toUint16(length); //payloadLength
        } else if (kind == uint8(MessageType.UpdateVault)) {
            length += 2 + message.toUint16(length); //payloadLength
        } else if (kind == uint8(MessageType.ManagerCallFromHub)) {
            length += 2 + message.toUint16(length); //payloadLength
        } else if (kind == uint8(MessageType.ManagerCallFromSpoke)) {
            length += 2 + message.toUint16(length); //payloadLength
        } else if (kind == uint8(MessageType.Request)) {
            length += 2 + message.toUint16(length); //payloadLength
        } else if (kind == uint8(MessageType.RequestCallback)) {
            length += 2 + message.toUint16(length); //payloadLength
        } else if (kind == uint8(MessageType.AuthorizeSpokeCall)) {
            length += 2 + message.toUint16(length); //payloadLength
        } else if (kind == uint8(MessageType.UnauthorizeSpokeCall)) {
            length += 2 + message.toUint16(length); //payloadLength
        } else if (kind == uint8(MessageType.SetPoolAdapters)) {
            length += message.toUint16(12) * 32; // message with variable length
        }
    }

    function messagePoolId(bytes memory message) internal pure returns (PoolId poolId) {
        uint8 kind = message.toUint8(0);

        // SetPoolAdapters is pool-independent in framing but configures a specific pool's adapter set,
        // and carries its PoolId in position 1. Reporting that PoolId lets the update route over the
        // pool's own adapters instead of the global set (MultiAdapter falls back to global while the
        // pool has no set yet, so initialization still works). All messages from NotifyPool onward
        // likewise carry a PoolId in position 1.
        if (kind == uint8(MessageType.SetPoolAdapters) || kind >= uint8(MessageType.NotifyPool)) {
            return PoolId.wrap(message.toUint64(1));
        }

        return PoolId.wrap(0);
    }

    /// @notice Returns the centrifugeId that `message` must originate from, or 0 if any source is permitted.
    ///
    ///         When adding a new message type, classify it here. A spoke->hub message MUST be added to
    ///         the exclusion list (or handled explicitly), otherwise it will be incorrectly rejected when
    ///         arriving from its source chain. This function is exhaustively checked in MessageLib.t.sol.
    function messageSourceCentrifugeId(bytes memory message) internal pure returns (uint16) {
        MessageType kind = MessageType(message.toUint8(0));

        // Hub->spoke: SetPoolAdapters and all messages from NotifyPool upward, except the spoke->hub
        // exclusions below. All hub->spoke messages carry their poolId at offset 1 (big-endian uint64).
        // Request and UpdateAssets are excluded here and handled by the asset-homed branch below.
        if (
            kind == MessageType.SetPoolAdapters
                || (kind >= MessageType.NotifyPool
                    && kind != MessageType.InitiateTransferShares
                    && kind != MessageType.UpdateAssets
                    && kind != MessageType.UpdateShares
                    && kind != MessageType.Request
                    && kind != MessageType.ManagerCallFromSpoke)
        ) {
            uint16 hub = messagePoolId(message).centrifugeId();
            // No real pool has centrifugeId 0; reject outright rather than falling through to
            // "0 = any source".
            require(hub != 0, InvalidPoolHome());
            return hub;
        }
        if (kind == MessageType.ScheduleUpgrade || kind == MessageType.CancelUpgrade) {
            return MAINNET_CENTRIFUGE_ID;
        }
        if (kind == MessageType.RegisterAsset || kind == MessageType.Request || kind == MessageType.UpdateAssets) {
            uint16 assetHome = messageAssetId(kind, message).centrifugeId();
            // ISO-4217 currency assets (centrifugeId 0) are registered locally on the Hub and are never
            // legitimately reported by a spoke; reject outright rather than falling through to
            // "0 = any source".
            require(assetHome != 0, InvalidAssetHome());
            return assetHome;
        }
        return 0;
    }

    /// @dev The AssetId embedded in `message`. RegisterAsset carries it at offset 1; Request and
    ///      UpdateAssets carry it at offset 25 (after poolId and scId).
    function messageAssetId(MessageType kind, bytes memory message) internal pure returns (AssetId) {
        if (kind == MessageType.RegisterAsset) {
            return AssetId.wrap(message.toUint128(1));
        }
        if (kind == MessageType.Request || kind == MessageType.UpdateAssets) {
            return AssetId.wrap(message.toUint128(25));
        }
        revert UnknownMessageType();
    }

    /// @notice The pool whose adapter set should route/verify `message`. Normally the message's own pool
    ///         (`messagePoolId`), with one exception: a SetPoolAdapters for a pool that has no adapter set
    ///         yet (`poolConfigured == false`) falls back to the global pool, because the pool's first
    ///         adapter configuration has to arrive over the global set. `poolConfigured` is supplied by the
    ///         adapter layer, which is the only place that knows whether the pool already has a set.
    function routePoolId(bytes memory message, bool poolConfigured) internal pure returns (PoolId) {
        if (!poolConfigured && messageType(message) == MessageType.SetPoolAdapters) {
            return PoolId.wrap(0);
        }
        return messagePoolId(message);
    }

    function messageExtraGasLimit(bytes memory message) internal pure returns (uint128) {
        uint8 kind = message.toUint8(0);

        if (kind == uint8(MessageType.NotifyShareClass)) {
            return message.toUint128(250);
        } else if (kind == uint8(MessageType.NotifyShareMetadata)) {
            return message.toUint128(185);
        } else if (kind == uint8(MessageType.InitiateTransferShares)) {
            return message.toUint128(91);
        } else if (kind == uint8(MessageType.ExecuteTransferShares)) {
            return message.toUint128(73);
        } else if (kind == uint8(MessageType.UpdateRestriction)) {
            return message.toUint128(25);
        } else if (kind == uint8(MessageType.ManagerCallFromHub)) {
            return message.toUint128(41);
        } else if (kind == uint8(MessageType.ManagerCallFromSpoke)) {
            return message.toUint128(73);
        } else if (kind == uint8(MessageType.Request)) {
            return message.toUint128(41);
        } else if (kind == uint8(MessageType.RequestCallback)) {
            return message.toUint128(41);
        } else if (kind == uint8(MessageType.UpdateVault)) {
            return message.toUint128(74);
        } else if (kind == uint8(MessageType.UpdateAssets)) {
            return message.toUint128(75);
        } else if (kind == uint8(MessageType.UpdateShares)) {
            return message.toUint128(59);
        }

        return 0;
    }

    //---------------------------------------
    //    ScheduleUpgrade
    //---------------------------------------

    struct ScheduleUpgrade {
        bytes32 target;
    }

    function deserializeScheduleUpgrade(bytes memory data) internal pure returns (ScheduleUpgrade memory) {
        require(messageType(data) == MessageType.ScheduleUpgrade, UnknownMessageType());
        return ScheduleUpgrade({target: data.toBytes32(1)});
    }

    function serialize(ScheduleUpgrade memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(MessageType.ScheduleUpgrade, t.target);
    }

    //---------------------------------------
    //    CancelUpgrade
    //---------------------------------------

    struct CancelUpgrade {
        bytes32 target;
    }

    function deserializeCancelUpgrade(bytes memory data) internal pure returns (CancelUpgrade memory) {
        require(messageType(data) == MessageType.CancelUpgrade, UnknownMessageType());
        return CancelUpgrade({target: data.toBytes32(1)});
    }

    function serialize(CancelUpgrade memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(MessageType.CancelUpgrade, t.target);
    }

    //---------------------------------------
    //    RegisterAsset
    //---------------------------------------

    struct RegisterAsset {
        uint128 assetId;
        uint8 decimals;
    }

    function deserializeRegisterAsset(bytes memory data) internal pure returns (RegisterAsset memory) {
        require(messageType(data) == MessageType.RegisterAsset, UnknownMessageType());
        return RegisterAsset({assetId: data.toUint128(1), decimals: data.toUint8(17)});
    }

    function serialize(RegisterAsset memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(MessageType.RegisterAsset, t.assetId, t.decimals);
    }

    //---------------------------------------
    //   SetPoolAdapters
    //---------------------------------------

    struct SetPoolAdapters {
        uint64 poolId;
        uint8 threshold;
        uint16 targetSessionId;
        bytes32[] adapterList;
    }

    function deserializeSetPoolAdapters(bytes memory data) internal pure returns (SetPoolAdapters memory) {
        require(messageType(data) == MessageType.SetPoolAdapters, UnknownMessageType());

        uint16 length = data.toUint16(12);
        bytes32[] memory adapterList = new bytes32[](length);
        for (uint256 i; i < length; i++) {
            adapterList[i] = data.toBytes32(14 + i * 32);
        }

        return SetPoolAdapters({
            poolId: data.toUint64(1),
            threshold: data.toUint8(9),
            targetSessionId: data.toUint16(10),
            adapterList: adapterList
        });
    }

    function serialize(SetPoolAdapters memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(
            MessageType.SetPoolAdapters,
            t.poolId,
            t.threshold,
            t.targetSessionId,
            t.adapterList.length.toUint16(),
            t.adapterList
        );
    }

    //---------------------------------------
    //    NotifyPool
    //---------------------------------------

    struct NotifyPool {
        uint64 poolId;
    }

    function deserializeNotifyPool(bytes memory data) internal pure returns (NotifyPool memory) {
        require(messageType(data) == MessageType.NotifyPool, UnknownMessageType());
        return NotifyPool({poolId: data.toUint64(1)});
    }

    function serialize(NotifyPool memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(MessageType.NotifyPool, t.poolId);
    }

    //---------------------------------------
    //    NotifyShareClass
    //---------------------------------------

    struct NotifyShareClass {
        uint64 poolId;
        bytes16 scId;
        string name; // Fixed to 128 bytes
        bytes32 symbol; // utf8
        uint8 decimals;
        bytes32 salt;
        bytes32 registrar;
        uint128 extraGasLimit;
        bytes payload; // Opaque, forwarded to the registrar on token creation
    }

    function deserializeNotifyShareClass(bytes memory data) internal pure returns (NotifyShareClass memory) {
        require(messageType(data) == MessageType.NotifyShareClass, UnknownMessageType());
        uint16 payloadLength = data.toUint16(266);
        return NotifyShareClass({
            poolId: data.toUint64(1),
            scId: data.toBytes16(9),
            name: data.slice(25, 128).bytes128ToString(),
            symbol: data.toBytes32(153),
            decimals: data.toUint8(185),
            salt: data.toBytes32(186),
            registrar: data.toBytes32(218),
            extraGasLimit: data.toUint128(250),
            payload: data.slice(268, payloadLength)
        });
    }

    function serialize(NotifyShareClass memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(
            MessageType.NotifyShareClass,
            t.poolId,
            t.scId,
            bytes(t.name).sliceZeroPadded(0, 128),
            t.symbol,
            t.decimals,
            t.salt,
            t.registrar,
            t.extraGasLimit,
            t.payload.length.toUint16(),
            t.payload
        );
    }

    //---------------------------------------
    //    NotifyPricePoolPerShare
    //---------------------------------------

    struct NotifyPricePoolPerShare {
        uint64 poolId;
        bytes16 scId;
        uint128 price;
        uint64 timestamp;
    }

    function deserializeNotifyPricePoolPerShare(bytes memory data)
        internal
        pure
        returns (NotifyPricePoolPerShare memory)
    {
        require(messageType(data) == MessageType.NotifyPricePoolPerShare, UnknownMessageType());
        return NotifyPricePoolPerShare({
            poolId: data.toUint64(1), scId: data.toBytes16(9), price: data.toUint128(25), timestamp: data.toUint64(41)
        });
    }

    function serialize(NotifyPricePoolPerShare memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(MessageType.NotifyPricePoolPerShare, t.poolId, t.scId, t.price, t.timestamp);
    }

    //---------------------------------------
    //    NotifyPricePoolPerAsset
    //---------------------------------------

    struct NotifyPricePoolPerAsset {
        uint64 poolId;
        bytes16 scId;
        uint128 assetId;
        uint128 price;
        uint64 timestamp;
    }

    function deserializeNotifyPricePoolPerAsset(bytes memory data)
        internal
        pure
        returns (NotifyPricePoolPerAsset memory)
    {
        require(messageType(data) == MessageType.NotifyPricePoolPerAsset, UnknownMessageType());
        return NotifyPricePoolPerAsset({
            poolId: data.toUint64(1),
            scId: data.toBytes16(9),
            assetId: data.toUint128(25),
            price: data.toUint128(41),
            timestamp: data.toUint64(57)
        });
    }

    function serialize(NotifyPricePoolPerAsset memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(MessageType.NotifyPricePoolPerAsset, t.poolId, t.scId, t.assetId, t.price, t.timestamp);
    }

    //---------------------------------------
    //    NotifyShareMetadata
    //---------------------------------------

    struct NotifyShareMetadata {
        uint64 poolId;
        bytes16 scId;
        string name; // Fixed to 128 bytes
        bytes32 symbol; // utf8
        uint128 extraGasLimit;
    }

    function deserializeNotifyShareMetadata(bytes memory data) internal pure returns (NotifyShareMetadata memory) {
        require(messageType(data) == MessageType.NotifyShareMetadata, UnknownMessageType());
        return NotifyShareMetadata({
            poolId: data.toUint64(1),
            scId: data.toBytes16(9),
            name: data.slice(25, 128).bytes128ToString(),
            symbol: data.toBytes32(153),
            extraGasLimit: data.toUint128(185)
        });
    }

    function serialize(NotifyShareMetadata memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(
            MessageType.NotifyShareMetadata,
            t.poolId,
            t.scId,
            bytes(t.name).sliceZeroPadded(0, 128),
            t.symbol,
            t.extraGasLimit
        );
    }

    //---------------------------------------
    //    InitiateTransferShares
    //---------------------------------------

    struct InitiateTransferShares {
        uint64 poolId;
        bytes16 scId;
        uint16 centrifugeId;
        bytes32 receiver;
        uint128 amount;
        uint128 remoteExtraGasLimit;
        uint128 extraGasLimit;
        // The originator of the transfer (the real sender), forwarded to the Hub-side bridging hook.
        bytes32 sender;
    }

    function deserializeInitiateTransferShares(bytes memory data)
        internal
        pure
        returns (InitiateTransferShares memory)
    {
        require(messageType(data) == MessageType.InitiateTransferShares, UnknownMessageType());
        return InitiateTransferShares({
            poolId: data.toUint64(1),
            scId: data.toBytes16(9),
            centrifugeId: data.toUint16(25),
            receiver: data.toBytes32(27),
            amount: data.toUint128(59),
            remoteExtraGasLimit: data.toUint128(75),
            extraGasLimit: data.toUint128(91),
            sender: data.toBytes32(107)
        });
    }

    function serialize(InitiateTransferShares memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(
            MessageType.InitiateTransferShares,
            t.poolId,
            t.scId,
            t.centrifugeId,
            t.receiver,
            t.amount,
            t.remoteExtraGasLimit,
            t.extraGasLimit,
            t.sender
        );
    }

    //---------------------------------------
    //    ExecuteTransferShares
    //---------------------------------------

    struct ExecuteTransferShares {
        uint64 poolId;
        bytes16 scId;
        bytes32 receiver;
        uint128 amount;
        uint128 extraGasLimit;
    }

    function deserializeExecuteTransferShares(bytes memory data) internal pure returns (ExecuteTransferShares memory) {
        require(messageType(data) == MessageType.ExecuteTransferShares, UnknownMessageType());
        return ExecuteTransferShares({
            poolId: data.toUint64(1),
            scId: data.toBytes16(9),
            receiver: data.toBytes32(25),
            amount: data.toUint128(57),
            extraGasLimit: data.toUint128(73)
        });
    }

    function serialize(ExecuteTransferShares memory t) internal pure returns (bytes memory) {
        return
            abi.encodePacked(MessageType.ExecuteTransferShares, t.poolId, t.scId, t.receiver, t.amount, t.extraGasLimit);
    }

    //---------------------------------------
    //    UpdateRestriction
    //---------------------------------------

    struct UpdateRestriction {
        uint64 poolId;
        bytes16 scId;
        uint128 extraGasLimit;
        bytes payload; // As sequence of bytes
    }

    function deserializeUpdateRestriction(bytes memory data) internal pure returns (UpdateRestriction memory) {
        require(messageType(data) == MessageType.UpdateRestriction, UnknownMessageType());

        uint16 payloadLength = data.toUint16(41);
        return UpdateRestriction({
            poolId: data.toUint64(1),
            scId: data.toBytes16(9),
            extraGasLimit: data.toUint128(25),
            payload: data.slice(43, payloadLength)
        });
    }

    function serialize(UpdateRestriction memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(
            MessageType.UpdateRestriction, t.poolId, t.scId, t.extraGasLimit, t.payload.length.toUint16(), t.payload
        );
    }

    //---------------------------------------
    //    ManagerCallFromHub
    //---------------------------------------

    /// @dev Generic hub->target manager call routed through the Envoy on the receiving chain. Pool-scoped;
    ///      any `scId` is encoded inside `payload` by the caller.
    struct ManagerCallFromHub {
        uint64 poolId;
        bytes32 target;
        uint128 extraGasLimit;
        bytes payload; // As sequence of bytes
    }

    function deserializeManagerCallFromHub(bytes memory data) internal pure returns (ManagerCallFromHub memory) {
        require(messageType(data) == MessageType.ManagerCallFromHub, UnknownMessageType());
        uint16 payloadLength = data.toUint16(57);
        return ManagerCallFromHub({
            poolId: data.toUint64(1),
            target: data.toBytes32(9),
            extraGasLimit: data.toUint128(41),
            payload: data.slice(59, payloadLength)
        });
    }

    function serialize(ManagerCallFromHub memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(
            MessageType.ManagerCallFromHub, t.poolId, t.target, t.extraGasLimit, t.payload.length.toUint16(), t.payload
        );
    }

    //---------------------------------------
    //    ManagerCallFromSpoke
    //---------------------------------------

    struct ManagerCallFromSpoke {
        uint64 poolId;
        bytes32 target;
        bytes32 sender;
        uint128 extraGasLimit;
        bytes payload; // As sequence of bytes
    }

    function deserializeManagerCallFromSpoke(bytes memory data) internal pure returns (ManagerCallFromSpoke memory) {
        require(messageType(data) == MessageType.ManagerCallFromSpoke, UnknownMessageType());
        uint16 payloadLength = data.toUint16(89);
        return ManagerCallFromSpoke({
            poolId: data.toUint64(1),
            target: data.toBytes32(9),
            sender: data.toBytes32(41),
            extraGasLimit: data.toUint128(73),
            payload: data.slice(91, payloadLength)
        });
    }

    function serialize(ManagerCallFromSpoke memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(
            MessageType.ManagerCallFromSpoke,
            t.poolId,
            t.target,
            t.sender,
            t.extraGasLimit,
            t.payload.length.toUint16(),
            t.payload
        );
    }

    //---------------------------------------
    //    Request
    //---------------------------------------

    struct Request {
        uint64 poolId;
        bytes16 scId;
        uint128 assetId;
        uint128 extraGasLimit;
        bytes payload; // As sequence of bytes
    }

    function deserializeRequest(bytes memory data) internal pure returns (Request memory) {
        require(messageType(data) == MessageType.Request, UnknownMessageType());
        uint16 payloadLength = data.toUint16(57);
        return Request({
            poolId: data.toUint64(1),
            scId: data.toBytes16(9),
            assetId: data.toUint128(25),
            extraGasLimit: data.toUint128(41),
            payload: data.slice(59, payloadLength)
        });
    }

    function serialize(Request memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(
            MessageType.Request, t.poolId, t.scId, t.assetId, t.extraGasLimit, t.payload.length.toUint16(), t.payload
        );
    }

    //---------------------------------------
    //    RequestCallback
    //---------------------------------------

    struct RequestCallback {
        uint64 poolId;
        bytes16 scId;
        uint128 assetId;
        uint128 extraGasLimit;
        bytes payload; // As sequence of bytes
    }

    function deserializeRequestCallback(bytes memory data) internal pure returns (RequestCallback memory) {
        require(messageType(data) == MessageType.RequestCallback, UnknownMessageType());
        uint16 payloadLength = data.toUint16(57);
        return RequestCallback({
            poolId: data.toUint64(1),
            scId: data.toBytes16(9),
            assetId: data.toUint128(25),
            extraGasLimit: data.toUint128(41),
            payload: data.slice(59, payloadLength)
        });
    }

    function serialize(RequestCallback memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(
            MessageType.RequestCallback,
            t.poolId,
            t.scId,
            t.assetId,
            t.extraGasLimit,
            t.payload.length.toUint16(),
            t.payload
        );
    }

    //---------------------------------------
    //   VaultUpdate
    //---------------------------------------

    struct UpdateVault {
        uint64 poolId;
        bytes16 scId;
        uint128 assetId;
        bytes32 vaultOrFactory;
        uint8 kind; // VaultUpdateKind
        uint128 extraGasLimit;
        bytes payload; // Opaque, forwarded to the factory on DeployAndLink
    }

    function deserializeUpdateVault(bytes memory data) internal pure returns (UpdateVault memory) {
        require(messageType(data) == MessageType.UpdateVault, UnknownMessageType());
        uint16 payloadLength = data.toUint16(90);
        return UpdateVault({
            poolId: data.toUint64(1),
            scId: data.toBytes16(9),
            assetId: data.toUint128(25),
            vaultOrFactory: data.toBytes32(41),
            kind: data.toUint8(73),
            extraGasLimit: data.toUint128(74),
            payload: data.slice(92, payloadLength)
        });
    }

    function serialize(UpdateVault memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(
            MessageType.UpdateVault,
            t.poolId,
            t.scId,
            t.assetId,
            t.vaultOrFactory,
            t.kind,
            t.extraGasLimit,
            t.payload.length.toUint16(),
            t.payload
        );
    }

    //---------------------------------------
    //   SetRequestManager
    //---------------------------------------

    struct SetRequestManager {
        uint64 poolId;
        bytes32 manager;
    }

    function deserializeSetRequestManager(bytes memory data) internal pure returns (SetRequestManager memory) {
        require(messageType(data) == MessageType.SetRequestManager, UnknownMessageType());
        return SetRequestManager({poolId: data.toUint64(1), manager: data.toBytes32(9)});
    }

    function serialize(SetRequestManager memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(MessageType.SetRequestManager, t.poolId, t.manager);
    }

    //---------------------------------------
    //    UpdateAssets
    //---------------------------------------

    struct UpdateAssets {
        uint64 poolId;
        bytes16 scId;
        uint128 assetId;
        uint128 amount;
        uint64 timestamp;
        bool isIncrease;
        bool isSnapshot;
        uint64 nonce;
        uint128 extraGasLimit;
    }

    function deserializeUpdateAssets(bytes memory data) internal pure returns (UpdateAssets memory h) {
        require(messageType(data) == MessageType.UpdateAssets, UnknownMessageType());

        return UpdateAssets({
            poolId: data.toUint64(1),
            scId: data.toBytes16(9),
            assetId: data.toUint128(25),
            amount: data.toUint128(41),
            timestamp: data.toUint64(57),
            isIncrease: data.toBool(65),
            isSnapshot: data.toBool(66),
            nonce: data.toUint64(67),
            extraGasLimit: data.toUint128(75)
        });
    }

    function serialize(UpdateAssets memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(
            MessageType.UpdateAssets,
            t.poolId,
            t.scId,
            t.assetId,
            t.amount,
            t.timestamp,
            t.isIncrease,
            t.isSnapshot,
            t.nonce,
            t.extraGasLimit
        );
    }

    //---------------------------------------
    //    UpdateShares
    //---------------------------------------

    struct UpdateShares {
        uint64 poolId;
        bytes16 scId;
        uint128 shares;
        uint64 timestamp;
        bool isIssuance;
        bool isSnapshot;
        uint64 nonce;
        uint128 extraGasLimit;
    }

    function deserializeUpdateShares(bytes memory data) internal pure returns (UpdateShares memory) {
        require(messageType(data) == MessageType.UpdateShares, UnknownMessageType());

        return UpdateShares({
            poolId: data.toUint64(1),
            scId: data.toBytes16(9),
            shares: data.toUint128(25),
            timestamp: data.toUint64(41),
            isIssuance: data.toBool(49),
            isSnapshot: data.toBool(50),
            nonce: data.toUint64(51),
            extraGasLimit: data.toUint128(59)
        });
    }

    function serialize(UpdateShares memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(
            MessageType.UpdateShares,
            t.poolId,
            t.scId,
            t.shares,
            t.timestamp,
            t.isIssuance,
            t.isSnapshot,
            t.nonce,
            t.extraGasLimit
        );
    }

    //---------------------------------------
    //   UpdateManager
    //---------------------------------------

    struct UpdateManager {
        uint64 poolId;
        uint8 kind;
        bytes32 who;
        bool canManage;
    }

    function deserializeUpdateManager(bytes memory data) internal pure returns (UpdateManager memory) {
        require(messageType(data) == MessageType.UpdateManager, UnknownMessageType());
        return UpdateManager({
            poolId: data.toUint64(1), kind: data.toUint8(9), who: data.toBytes32(10), canManage: data.toBool(42)
        });
    }

    function serialize(UpdateManager memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(MessageType.UpdateManager, t.poolId, t.kind, t.who, t.canManage);
    }

    //---------------------------------------
    //   SetPolicy
    //---------------------------------------

    struct SetPolicy {
        uint64 poolId;
        bytes32 policy;
    }

    function deserializeSetPolicy(bytes memory data) internal pure returns (SetPolicy memory) {
        require(messageType(data) == MessageType.SetPolicy, UnknownMessageType());
        return SetPolicy({poolId: data.toUint64(1), policy: data.toBytes32(9)});
    }

    function serialize(SetPolicy memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(MessageType.SetPolicy, t.poolId, t.policy);
    }

    //---------------------------------------
    //   AuthorizeSpokeCall
    //---------------------------------------

    struct AuthorizeSpokeCall {
        uint64 poolId;
        bytes payload; // The exact spoke calldata being authorized
    }

    function deserializeAuthorizeSpokeCall(bytes memory data) internal pure returns (AuthorizeSpokeCall memory) {
        require(messageType(data) == MessageType.AuthorizeSpokeCall, UnknownMessageType());

        uint16 payloadLength = data.toUint16(9);
        return AuthorizeSpokeCall({poolId: data.toUint64(1), payload: data.slice(11, payloadLength)});
    }

    function serialize(AuthorizeSpokeCall memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(MessageType.AuthorizeSpokeCall, t.poolId, t.payload.length.toUint16(), t.payload);
    }

    //---------------------------------------
    //   UnauthorizeSpokeCall
    //---------------------------------------

    struct UnauthorizeSpokeCall {
        uint64 poolId;
        bytes payload; // The exact spoke calldata whose authorization is being revoked
    }

    function deserializeUnauthorizeSpokeCall(bytes memory data) internal pure returns (UnauthorizeSpokeCall memory) {
        require(messageType(data) == MessageType.UnauthorizeSpokeCall, UnknownMessageType());

        uint16 payloadLength = data.toUint16(9);
        return UnauthorizeSpokeCall({poolId: data.toUint64(1), payload: data.slice(11, payloadLength)});
    }

    function serialize(UnauthorizeSpokeCall memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(MessageType.UnauthorizeSpokeCall, t.poolId, t.payload.length.toUint16(), t.payload);
    }
}

src/core/spoke/factories/interfaces/IEscrowFactory.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {PoolId} from "../../../types/PoolId.sol";
import {IEscrow} from "../../interfaces/IEscrow.sol";

/// @title  IEscrowProvider
/// @notice Interface for deterministic escrow address resolution
interface IEscrowProvider {
    /// @notice Returns the deterministic address of an escrow contract based on a given pool id
    ///         wrapped into the corresponding interface.
    ///
    /// @dev Does not check, whether the escrow was already deployed.
    function escrow(PoolId poolId) external view returns (IEscrow);

    /// @notice Returns the pool id for a given escrow address.
    ///
    /// @dev Returns the null pool id if the address is not a known escrow deployed by this factory.
    function poolId(address escrow) external view returns (PoolId);
}

/// @title  IEscrowFactory
/// @notice Factory for deploying deterministic escrow contracts
/// @dev    Each pool has a unique escrow contract shared across all its share classes
interface IEscrowFactory is IEscrowProvider {
    event DeployEscrow(PoolId indexed poolId, address indexed escrow);
    event File(bytes32 what, address data);

    error FileUnrecognizedParam();

    /// @notice Root authority that manages ward permissions and timelocked upgrades
    function root() external view returns (address);

    /// @notice Spoke which manages the escrow of each pool
    function spoke() external view returns (address);

    /// @notice Deploys new escrow and returns it.
    /// @dev All share classes of a pool are represented by the same escrow contract.
    ///
    /// @param poolId Id of the pool this escrow is deployed for
    /// @return IEscrow The the newly deployed escrow contract
    function newEscrow(PoolId poolId) external returns (IEscrow);

    /// @notice Updates contract parameters of type address.
    function file(bytes32 what, address data) external;
}

src/core/spoke/factories/interfaces/IVaultFactory.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {PoolId} from "../../../types/PoolId.sol";
import {ShareClassId} from "../../../types/ShareClassId.sol";

/// @title  IVaultFactory
/// @notice Factory for deploying vault contracts for pool share classes
/// @dev    Creates vaults linking pool IDs, share class IDs, assets, and tokens.
///
///         Factory convention: a factory MUST expose a deterministic pre-deployment address view
///         ({getVault}), so addresses (used as primary keys, and cross-chain) are knowable before
///         deployment. The deployment event is emitted by the registry ({ISpokeRegistry.DeployVault}),
///         the sole caller of {newVault}, so a separate factory-level event is not needed.
interface IVaultFactory {
    error UnsupportedTokenId();

    /// @notice The deterministic address {newVault} deploys (or has deployed) for these parameters.
    /// @dev    Computed from the factory's CREATE2 salt and init code, so it is valid before deployment.
    ///         Takes `payload` because a factory may derive the vault's address from it.
    function getVault(
        PoolId poolId,
        ShareClassId scId,
        address asset,
        uint256 tokenId,
        address token,
        bytes calldata payload
    ) external view returns (address vault);

    /// @notice Deploys new vault for `poolId`, `scId` and `asset`.
    ///
    /// @param poolId Id of the pool. Id is one of the already supported pools.
    /// @param scId Id of the share class token. Id is one of the already supported share class tokens.
    /// @param asset Address of the underlying asset that is getting deposited inside the pool.
    /// @param tokenId Token id of the underlying asset that is getting deposited inside the pool.
    ///              I.e. zero if asset corresponds to ERC20 or non-zero if asset corresponds to ERC6909.
    /// @param token Address of the share class token that is getting issues against the deposited asset.
    /// @param payload Opaque, factory-defined deployment data forwarded from the hub. The core does not
    ///               inspect or validate it in any way; interpreting it is entirely the factory's
    ///               responsibility. Empty for factories that need no extra configuration; such factories
    ///               must ignore it.
    function newVault(
        PoolId poolId,
        ShareClassId scId,
        address asset,
        uint256 tokenId,
        address token,
        bytes calldata payload
    ) external returns (address);
}

src/core/spoke/interfaces/IEscrow.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {IRecoverable} from "../../../misc/Recoverable.sol";

import {PoolId} from "../../types/PoolId.sol";
import {ShareClassId} from "../../types/ShareClassId.sol";

struct Holding {
    uint128 total;
    uint128 reserved;
}

/// @title Escrow separating funds by pool and share class
interface IEscrow is IRecoverable {
    //----------------------------------------------------------------------------------------------
    // Events
    //----------------------------------------------------------------------------------------------

    /// @notice Emitted when an authTransferTo is made
    /// @dev Needed as allowances increase attack surface
    event AuthTransferTo(address indexed asset, uint256 indexed tokenId, address receiver, uint256 value);

    /// @notice Emitted when a deposit is made
    /// @param asset The address of the deposited asset
    /// @param tokenId The id of the asset - 0 for ERC20
    /// @param poolId The id of the pool
    /// @param scId The id of the share class
    /// @param value The amount deposited
    event Deposit(
        address indexed asset, uint256 indexed tokenId, PoolId indexed poolId, ShareClassId scId, uint128 value
    );

    /// @notice Emitted when an amount is reserved
    /// @param asset The address of the reserved asset
    /// @param tokenId The id of the asset - 0 for ERC20
    /// @param poolId The id of the pool
    /// @param scId The id of the share class
    /// @param caller The address of the manager creating the reservation
    /// @param reason The reason code for the reservation
    /// @param delta The delta amount reserved
    /// @param value The new absolute amount reserved
    event IncreaseReserve(
        address indexed asset,
        uint256 indexed tokenId,
        PoolId indexed poolId,
        ShareClassId scId,
        address caller,
        bytes32 reason,
        uint128 delta,
        uint128 value
    );

    /// @notice Emitted when an amount is unreserved
    /// @param asset The address of the reserved asset
    /// @param tokenId The id of the asset - 0 for ERC20
    /// @param poolId The id of the pool
    /// @param scId The id of the share class
    /// @param caller The address of the manager that created the reservation
    /// @param reason The reason code that was used when reserving
    /// @param delta The delta amount unreserved
    /// @param value The new absolute amount reserved
    event DecreaseReserve(
        address indexed asset,
        uint256 indexed tokenId,
        PoolId indexed poolId,
        ShareClassId scId,
        address caller,
        bytes32 reason,
        uint128 delta,
        uint128 value
    );

    /// @notice Emitted when a withdraw is made
    /// @param asset The address of the withdrawn asset
    /// @param tokenId The id of the asset - 0 for ERC20
    /// @param poolId The id of the pool
    /// @param scId The id of the share class
    /// @param receiver The address receiving the withdrawn assets
    /// @param value The amount withdrawn
    event Withdraw(
        address indexed asset,
        uint256 indexed tokenId,
        PoolId indexed poolId,
        ShareClassId scId,
        address receiver,
        uint128 value
    );

    //----------------------------------------------------------------------------------------------
    // Errors
    //----------------------------------------------------------------------------------------------

    /// @notice Dispatched when the outstanding reserved amount is insufficient for the decrease
    error InsufficientReserve();

    /// @notice Dispatched when the escrow has insufficient balance for an action - virtual or actual balance
    error InsufficientBalance(address asset, uint256 tokenId, uint256 value, uint256 balance);

    //----------------------------------------------------------------------------------------------
    // Functions
    //----------------------------------------------------------------------------------------------

    /// @notice Transfers assets from the escrow to a receiver address
    /// @param asset The address of the asset to transfer
    /// @param tokenId The token ID of the asset (0 for ERC20, non-zero for ERC6909)
    /// @param receiver The address receiving the transferred assets
    /// @param value The amount of assets to transfer
    function authTransferTo(address asset, uint256 tokenId, address receiver, uint256 value) external;

    /// @notice Deposits `value` of `asset` in underlying `poolId` and given `scId`
    /// @dev NOTE: Must ensure balance sufficiency, i.e. that the depositing amount does not exceed the balance of escrow
    /// @param scId The id of the share class
    /// @param asset The address of the asset to be deposited
    /// @param tokenId The id of the asset - 0 for ERC20
    /// @param value The amount to deposit
    function deposit(ShareClassId scId, address asset, uint256 tokenId, uint128 value) external;

    /// @notice Withdraws `value` of `asset` in underlying `poolId` and given `scId`
    /// @dev Accounting only: decreases `total` by `value` and reverts unless the available
    ///      (non-reserved) balance covers `value`. The caller pairs it with `authTransferTo`
    ///      to move the actual tokens.
    /// @param scId The id of the share class
    /// @param asset The address of the asset to be withdrawn
    /// @param tokenId The id of the asset - 0 for ERC20
    /// @param receiver The address receiving the withdrawn assets
    /// @param value The amount to withdraw
    function withdraw(ShareClassId scId, address asset, uint256 tokenId, address receiver, uint128 value) external;

    /// @notice Increases the reserved amount of `value` for `asset` in underlying `poolId` and given `scId`
    /// @dev Reserves funds in the bucket keyed by `caller` and `reason`. These are unauthenticated accounting keys
    ///      (not checked against `msg.sender`); access is gated only by `auth` (the trusted Spoke). Per-key isolation
    ///      holds, but which key is used is the trusted caller's choice. See {ISpoke.reserve} for the trust model.
    /// @param scId The id of the share class
    /// @param asset The address of the asset to be reserved
    /// @param tokenId The id of the asset - 0 for ERC20
    /// @param value The amount to reserve
    /// @param caller The bucket owner recorded for the reservation (an accounting key supplied by the Spoke, not an
    ///               authenticated identity)
    /// @param reason The reservation bucket; an accounting key, not an authenticated identity
    function reserve(ShareClassId scId, address asset, uint256 tokenId, uint128 value, address caller, bytes32 reason)
        external;

    /// @notice Decreases the reserved amount of `value` for `asset` in underlying `poolId` and given `scId`
    /// @dev Unreserves funds from a specific bucket. MUST fail if bucket has insufficient funds.
    /// @dev As with {reserve}, `caller` and `reason` are unauthenticated accounting keys: any authorized caller can
    ///      unreserve any bucket, including one another manager booked. See {ISpoke.unreserve} for the trust model.
    /// @param scId The id of the share class
    /// @param asset The address of the asset to be unreserved
    /// @param tokenId The id of the asset - 0 for ERC20
    /// @param value The amount to decrease
    /// @param caller The bucket owner recorded for the reservation (an accounting key, not an authenticated identity)
    /// @param reason The reason code that was used when reserving; an accounting key, not an authenticated identity
    function unreserve(ShareClassId scId, address asset, uint256 tokenId, uint128 value, address caller, bytes32 reason)
        external;

    /// @notice Provides the available balance of `asset` in underlying `poolId` and given `scId`
    /// @dev MUST return the balance minus the reserved amount
    /// @param scId The id of the share class
    /// @param asset The address of the asset to be checked
    /// @param tokenId The id of the asset - 0 for ERC20
    /// @return The available balance
    function availableBalanceOf(ShareClassId scId, address asset, uint256 tokenId) external view returns (uint128);

    /// @notice Returns the pool id of this escrow
    /// @return The pool id
    function poolId() external view returns (PoolId);

    /// @notice Returns the holding details for a given share class, asset and token id
    /// @param scId The id of the share class
    /// @param asset The address of the asset
    /// @param tokenId The id of the asset - 0 for ERC20
    /// @return total The total amount held
    /// @return reserved The reserved amount
    function holding(ShareClassId scId, address asset, uint256 tokenId)
        external
        view
        returns (uint128 total, uint128 reserved);

    /// @notice Returns the reserved amount for a specific reserver, reason, asset and token id
    /// @param scId The id of the share class
    /// @param reserver The address of the reserver
    /// @param reason The reason code for the reservation
    /// @param asset The address of the asset
    /// @param tokenId The id of the asset - 0 for ERC20
    /// @return The reserved amount
    function reservedBy(ShareClassId scId, address reserver, bytes32 reason, address asset, uint256 tokenId)
        external
        view
        returns (uint128);
}

src/core/spoke/interfaces/IRegistrar.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title  IRegistrar
/// @notice Standard-specific driver for a share token implementation. The core only interacts with share
///         tokens through a registrar: it creates tokens, issues and cancels shares, applies restriction
///         updates, and maintains metadata. One registrar is deployed per token standard per chain, and
///         each share class selects its registrar at creation (via the `NotifyShareClass` message).
/// @dev    Registrar implementations MUST restrict all state-changing methods to the core spoke contracts
///         (Spoke, SpokeHandler, SpokeRegistry). A registrar is chosen per share class, and holds that share
///         class's mint authority on its chain. Because share supply is fungible across chains, a hostile
///         registrar on one chain can mint into the same share class on another via a crosschain transfer.
/// @dev    The registrar abstracts only privileged operations; core still moves shares via the token's
///         ERC20 `transfer`/`transferFrom`/`approve` directly, so every registrar's token MUST be
///         ERC20-transfer-compatible.
/// @dev    Because the core no longer force-transfers, a registrar's token MUST permit plain ERC20
///         transfers into the root-endorsed core contract (Spoke): cross-chain transfers pull the
///         shares in with `transferFrom` and `revoke`/`burn` pulls them in before burning. A restriction
///         policy that blocks transfers to that endorsed address will brick those flows.
interface IRegistrar {
    /// @notice Deploys (or registers) a new share token for this standard.
    /// @dev    In order to have the same address on different EVMs, `salt` should be used
    ///         during the creation process.
    /// @param  name Name of the new token
    /// @param  symbol Symbol of the new token
    /// @param  decimals Decimals of the new token
    /// @param  salt Salt used for deterministic deployments
    /// @param  payload Opaque, registrar-defined creation data forwarded from the hub. The core does not
    ///         inspect or validate it in any way; interpreting it is entirely the registrar's
    ///         responsibility. Empty for registrars that need no extra configuration; such registrars
    ///         must ignore it.
    /// @return token The address of the new token
    function newToken(string memory name, string memory symbol, uint8 decimals, bytes32 salt, bytes memory payload)
        external
        returns (address token);

    /// @notice Returns the address `newToken` would deploy for the given parameters, without deploying.
    /// @dev    Enables same-address deployments across EVMs to be verified ahead of creation. Takes `payload`
    ///         because a registrar may derive the token's address from it.
    function previewTokenAddress(
        string memory name,
        string memory symbol,
        uint8 decimals,
        bytes32 salt,
        bytes memory payload
    ) external view returns (address token);

    /// @notice Mints `amount` of `token` to `to`.
    function mint(address token, address to, uint256 amount) external;

    /// @notice Burns `amount` of `token` held by `from`.
    /// @dev    `from` is the calling core contract, which has pulled the shares to itself from the
    ///         consenting initiator. It grants the registrar an ERC20 allowance of `amount` beforehand
    ///         (the registrar re-pulls to the caller before burning, preserving the transfer-hook flow
    ///         shape); registrars whose token supports a privileged `authTransferFrom` need no allowance.
    function burn(address token, address from, uint256 amount) external;

    /// @notice Transfers `amount` of `token` from `from` to `to` without the owner's on-chain approval.
    /// @dev    OPTIONAL capability: implementations for standards without a privileged transfer
    ///         mechanism MUST revert.
    /// @param  sender The address initiating the transfer (forwarded to hooks/policies)
    function authTransferFrom(address token, address sender, address from, address to, uint256 amount) external;

    /// @notice Updates the name and symbol of `token`.
    /// @dev    MUST revert if neither name nor symbol changes.
    function updateMetadata(address token, string memory name, string memory symbol) external;

    /// @notice Applies a restriction update (e.g. freeze, membership) to `token`.
    /// @dev    The payload encoding is standard-specific; the default implementation forwards to the
    ///         token's transfer hook. Implementations without restriction support MUST revert.
    function updateRestriction(address token, bytes memory update) external;

    /// @notice Returns whether `from` may bridge `amount` of `token` to `centrifugeId`.
    /// @dev    The destination chain is encoded as a pseudo-address (`address(uint160(centrifugeId))`) for
    ///         the transfer-restriction check. Implementations without restriction support MUST return true.
    function canBridge(address token, address from, uint16 centrifugeId, uint256 amount) external view returns (bool);
}

src/core/spoke/interfaces/IRequestRouter.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {PoolId} from "../../types/PoolId.sol";
import {AssetId} from "../../types/AssetId.sol";
import {ShareClassId} from "../../types/ShareClassId.sol";

/// @notice The spoke-side entry point a request manager calls to forward a request to the Hub. Extracted into
///         its own interface (mirroring the callback side, `IRequestManager.callback`) so a request-manager
///         dispatcher can implement the same `request` shape and sit transparently between sub-managers and the
///         Spoke: a sub-manager targets either the Spoke or the dispatcher through this interface.
interface IRequestRouter {
    /// @notice Handles a request originating from the Spoke side
    /// @param poolId The pool id
    /// @param scId The share class id
    /// @param assetId The asset id
    /// @param payload The request payload to be processed
    /// @param extraGasLimit Additional gas stipend for cross-chain execution
    /// @param unpaid Whether to allow unpaid mode
    /// @param refund Address to refund excess payment
    function request(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        bytes memory payload,
        uint128 extraGasLimit,
        bool unpaid,
        address refund
    ) external payable;
}

src/core/spoke/interfaces/ISnapshotQueue.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {ISpokeMessageSender} from "../../messaging/interfaces/IGatewaySenders.sol";

import {PoolId} from "../../types/PoolId.sol";
import {AssetId} from "../../types/AssetId.sol";
import {ShareClassId} from "../../types/ShareClassId.sol";

struct ShareQueueAmount {
    // Net queued shares
    uint128 delta;
    // Whether the net queued shares lead to an issuance or revocation
    bool isPositive;
    // Number of queued asset IDs for this share class
    uint32 queuedAssetCounter;
    // Nonce for share + asset messages to the hub
    uint64 nonce;
}

struct AssetQueueAmount {
    // Gross queued deposit amount (asset units)
    uint128 deposits;
    // Gross queued withdrawal amount (asset units)
    uint128 withdrawals;
}

interface ISnapshotQueue {
    //----------------------------------------------------------------------------------------------
    // Events
    //----------------------------------------------------------------------------------------------

    event QueueAssets(
        PoolId indexed poolId, ShareClassId indexed scId, AssetId indexed assetId, uint128 amount, bool isIncrease
    );
    event QueueShares(PoolId indexed poolId, ShareClassId indexed scId, uint128 shares, bool isIssuance);
    event SubmitQueuedShares(PoolId indexed poolId, ShareClassId indexed scId, ISpokeMessageSender.UpdateData data);
    event SubmitQueuedAssets(
        PoolId indexed poolId, ShareClassId indexed scId, AssetId indexed assetId, ISpokeMessageSender.UpdateData data
    );

    //----------------------------------------------------------------------------------------------
    // Queue updates
    //----------------------------------------------------------------------------------------------

    /// @notice Accumulate a gross asset flow into the queue.
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @param amount The asset amount (a zero amount is a no-op)
    /// @param isIncrease Whether the flow is a deposit (true) or a withdrawal (false)
    function queueAssets(PoolId poolId, ShareClassId scId, AssetId assetId, uint128 amount, bool isIncrease) external;

    /// @notice Apply a share delta to the queued net (issuance adds, revocation subtracts).
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param shares The number of shares
    /// @param isIssuance Whether the delta is an issuance (true) or a revocation (false)
    function queueShares(PoolId poolId, ShareClassId scId, uint128 shares, bool isIssuance) external;

    //----------------------------------------------------------------------------------------------
    // Flushing
    //----------------------------------------------------------------------------------------------

    /// @notice Consume the queued asset flow, returning the net update to be sent to the Hub.
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @return data The net queued amount, snapshot flag, and nonce for the Hub message
    function flushAssets(PoolId poolId, ShareClassId scId, AssetId assetId)
        external
        returns (ISpokeMessageSender.UpdateData memory data);

    /// @notice Consume the queued share delta, returning the net update to be sent to the Hub.
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @return data The net queued shares, snapshot flag, and nonce for the Hub message
    function flushShares(PoolId poolId, ShareClassId scId) external returns (ISpokeMessageSender.UpdateData memory data);

    //----------------------------------------------------------------------------------------------
    // View methods
    //----------------------------------------------------------------------------------------------

    /// @notice Returns the queued shares for a share class
    function queuedShares(PoolId poolId, ShareClassId scId)
        external
        view
        returns (uint128 delta, bool isPositive, uint32 queuedAssetCounter, uint64 nonce);

    /// @notice Returns the queued assets for a share class and asset
    /// @return deposits Queued deposit amount
    /// @return withdrawals Queued withdrawal amount
    function queuedAssets(PoolId poolId, ShareClassId scId, AssetId assetId)
        external
        view
        returns (uint128 deposits, uint128 withdrawals);
}

src/core/spoke/interfaces/ISpoke.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {IEscrow} from "./IEscrow.sol";
import {IRequestRouter} from "./IRequestRouter.sol";
import {ISnapshotQueue} from "./ISnapshotQueue.sol";
import {ISpokeRegistry} from "./ISpokeRegistry.sol";

import {ISpokeMessageSender} from "../../messaging/interfaces/IGatewaySenders.sol";

import {PoolId} from "../../types/PoolId.sol";
import {AssetId} from "../../types/AssetId.sol";
import {ShareClassId} from "../../types/ShareClassId.sol";
import {IPolicy} from "../../utils/interfaces/IPolicy.sol";
import {IEscrowProvider} from "../factories/interfaces/IEscrowFactory.sol";
import {IBatchedMulticall} from "../../utils/interfaces/IBatchedMulticall.sol";

interface ISpoke is IBatchedMulticall, IRequestRouter {
    //----------------------------------------------------------------------------------------------
    // Events
    //----------------------------------------------------------------------------------------------

    event File(bytes32 indexed what, address data);
    event RegisterAsset(
        uint16 centrifugeId,
        AssetId indexed assetId,
        address indexed asset,
        uint256 indexed tokenId,
        string name,
        string symbol,
        uint8 decimals,
        bool isInitialization
    );
    event InitiateTransferShares(
        uint16 centrifugeId,
        PoolId indexed poolId,
        ShareClassId indexed scId,
        address indexed sender,
        address owner,
        bytes32 destinationAddress,
        uint128 amount
    );
    event ManagerCall(
        uint16 indexed centrifugeId, PoolId indexed poolId, bytes32 target, bytes payload, address indexed sender
    );
    event Withdraw(
        PoolId indexed poolId,
        ShareClassId indexed scId,
        address asset,
        uint256 tokenId,
        address receiver,
        uint128 amount
    );
    event WithdrawShares(PoolId indexed poolId, ShareClassId indexed scId, address receiver, uint128 shares);
    event Deposit(
        PoolId indexed poolId, ShareClassId indexed scId, address sender, address asset, uint256 tokenId, uint128 amount
    );
    /// @dev Emitted instead of `Deposit` when the assets are credited to the escrow without an accompanying
    ///      token transfer, so indexers can reconcile escrow balances from `Deposit`/`Withdraw` transfers alone.
    event NoteDeposit(
        PoolId indexed poolId, ShareClassId indexed scId, address sender, address asset, uint256 tokenId, uint128 amount
    );
    event Issue(PoolId indexed poolId, ShareClassId indexed scId, address sender, address to, uint128 shares);
    event Revoke(PoolId indexed poolId, ShareClassId indexed scId, address sender, address from, uint128 shares);
    event TransferSharesFrom(
        PoolId indexed poolId,
        ShareClassId indexed scId,
        address sender,
        address indexed from,
        address to,
        uint256 amount
    );

    //----------------------------------------------------------------------------------------------
    // Errors
    //----------------------------------------------------------------------------------------------

    error FileUnrecognizedParam();
    error TooManyDecimals();
    error AssetMissingDecimals();
    error LocalTransferNotAllowed();
    /// @notice Dispatched when a cross-chain share transfer names a zero amount: the origin-chain
    ///         burn would be final, with nothing meaningful to execute remotely.
    error EmptyAmount();
    error BridgeNotAllowed();
    error InvalidRequestManager();
    error NotBridger();
    error NotManager();

    //----------------------------------------------------------------------------------------------
    // Administration
    //----------------------------------------------------------------------------------------------

    /// @notice Updates a contract parameter
    /// @param what Accepts "gateway" and "sender".
    /// @param data The new address
    function file(bytes32 what, address data) external;

    //----------------------------------------------------------------------------------------------
    // Outgoing methods
    //----------------------------------------------------------------------------------------------

    /// @notice Registers an ERC-20 or ERC-6909 asset in another chain.
    /// @dev `decimals()` MUST return a `uint8` value between 0 and 18.
    /// @dev `name()` and `symbol()` MAY return no values.
    ///
    /// @param centrifugeId The centrifuge id of chain to where the shares are transferred
    /// @param asset The address of the asset to be registered
    /// @param tokenId The token id corresponding to the asset, i.e. zero if ERC20 or non-zero if ERC6909.
    /// @param refund Address to refund the excess of the payment
    /// @return assetId The underlying internal uint128 assetId.
    function registerAsset(uint16 centrifugeId, address asset, uint256 tokenId, address refund)
        external
        payable
        returns (AssetId assetId);

    /// @notice Initializes a holding on the hub for a pool's share class and asset. Callable by a spoke manager.
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    //----------------------------------------------------------------------------------------------
    // Balance sheet: asset methods
    //----------------------------------------------------------------------------------------------

    /// @notice Deposit assets into the escrow of the pool, counting them into the hub-accounted holding.
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param asset The asset address
    /// @param tokenId The token ID (SHOULD be 0 for ERC20 assets. ERC6909 assets with tokenId=0 are not supported)
    /// @param amount The amount to deposit
    function deposit(PoolId poolId, ShareClassId scId, address asset, uint256 tokenId, uint128 amount) external payable;

    /// @notice Count assets already held by the pool's escrow into the hub-accounted holding, without moving tokens.
    /// @dev    For reconciling assets that reached the escrow outside a `deposit` (donation, accidental transfer,
    ///         surplus). Does not verify the escrow balance, so a manager can over-credit: use with care.
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param asset The asset address
    /// @param tokenId The token ID (SHOULD be 0 for ERC20 assets. ERC6909 assets with tokenId=0 are not supported)
    /// @param amount The amount to count into the holding
    function noteDeposit(PoolId poolId, ShareClassId scId, address asset, uint256 tokenId, uint128 amount)
        external
        payable;

    /// @notice Withdraw assets from the pool's escrow, decreasing the hub-accounted holding.
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param asset The asset address
    /// @param tokenId The token ID (SHOULD be 0 for ERC20 assets. ERC6909 assets with tokenId=0 are not supported)
    /// @param receiver The address to receive the withdrawn assets
    /// @param amount The amount to withdraw
    function withdraw(
        PoolId poolId,
        ShareClassId scId,
        address asset,
        uint256 tokenId,
        address receiver,
        uint128 amount
    ) external payable;

    /// @notice Withdraw previously-reserved assets from the pool escrow.
    /// @dev    The hub holding decrease was already queued when the funds were reserved, so this does not queue again.
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param asset The asset address
    /// @param tokenId The token ID (SHOULD be 0 for ERC20 assets. ERC6909 assets with tokenId=0 are not supported)
    /// @param receiver The address to receive the withdrawn assets
    /// @param amount The amount to withdraw
    /// @param reserver The address that owns the reservation
    /// @param reason The reason code that was used when reserving
    function withdrawReserved(
        PoolId poolId,
        ShareClassId scId,
        address asset,
        uint256 tokenId,
        address receiver,
        uint128 amount,
        address reserver,
        bytes32 reason
    ) external payable;

    /// @notice Reserve assets, removing them from the hub-accounted holding.
    /// @dev These assets are removed from the available balance and from the hub holding (accounted = total - reserved),
    ///      queueing a holding decrease. It is possible to reserve more than the current balance, to lock future
    ///      expected assets.
    /// @dev Trust model: `reserver` and `reason` are unauthenticated accounting keys, not checked against
    ///      `msg.sender`. Any balance-sheet manager can reserve or unreserve any `(reserver, reason)` bucket
    ///      (including another manager's, e.g. the request manager's pending deposits) and withdraw the freed funds,
    ///      so grant the role only to parties trusted with the pool's full balance sheet. Core stays permissive on
    ///      purpose: requiring `reserver == msg.sender` would strand a reserving manager's funds if it broke. A pool
    ///      can restrict this in its policy instead, delaying `reserver != msg.sender` calls.
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param asset The asset address
    /// @param tokenId The token ID
    /// @param amount The amount to reserve
    /// @param reserver The address recorded as the reservation's owner in Escrow (an accounting key, not an
    ///                 authenticated identity)
    /// @param reason The reservation bucket; an accounting key, not an authenticated identity
    function reserve(
        PoolId poolId,
        ShareClassId scId,
        address asset,
        uint256 tokenId,
        uint128 amount,
        address reserver,
        bytes32 reason
    ) external payable;

    /// @notice Unreserve assets, returning them to the hub-accounted holding.
    /// @dev Re-adds the funds to the available balance and the hub holding, queueing a holding increase.
    /// @dev Trust model: `reserver` and `reason` are unauthenticated accounting keys; any balance-sheet manager can
    ///      unreserve any bucket (including another manager's) and withdraw the freed funds. See {reserve}.
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param asset The asset address
    /// @param tokenId The token ID
    /// @param amount The amount to unreserve
    /// @param reserver The address recorded as the reservation's owner (an accounting key, not an authenticated
    ///                 identity)
    /// @param reason The reason code that was used when reserving; an accounting key, not an authenticated identity
    function unreserve(
        PoolId poolId,
        ShareClassId scId,
        address asset,
        uint256 tokenId,
        uint128 amount,
        address reserver,
        bytes32 reason
    ) external payable;

    /// @notice Sends the queued updated holding amount to the Hub, which values it at its own valuation
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @param extraGasLimit Extra gas limit for cross-chain execution
    /// @param refund Address to receive excess gas refund
    function submitQueuedAssets(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        uint128 extraGasLimit,
        address refund
    ) external payable;

    //----------------------------------------------------------------------------------------------
    // Balance sheet: share methods
    //----------------------------------------------------------------------------------------------

    /// @notice Issue new share tokens
    /// @dev Increases the total issuance
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param to The address to issue shares to
    /// @param shares The number of shares to issue
    function issue(PoolId poolId, ShareClassId scId, address to, uint128 shares) external payable;

    /// @notice Revoke share tokens
    /// @dev Decreases the total issuance. Pulls the shares from msgSender(), who must hold them and have
    ///      approved the Spoke as spender
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param shares The number of shares to revoke
    function revoke(PoolId poolId, ShareClassId scId, uint128 shares) external payable;

    /// @notice Transfer share tokens parked in the pool escrow out to a receiver (hook-checked).
    /// @dev    Share issuance is accounted separately via issue/revoke, so this carries no hub queue.
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param receiver The address to receive the shares
    /// @param amount The amount of shares to transfer
    function withdrawShares(PoolId poolId, ShareClassId scId, address receiver, uint128 amount) external payable;

    /// @notice Sends the queued updated shares changed to the Hub
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param extraGasLimit Extra gas limit for cross-chain execution
    /// @param refund Address to receive excess gas refund
    function submitQueuedShares(PoolId poolId, ShareClassId scId, uint128 extraGasLimit, address refund)
        external
        payable;

    /// @notice Force-transfers share tokens
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param sender The address initiating the transfer
    /// @param from The address to transfer from
    /// @param to The address to transfer to
    /// @param amount The amount to transfer
    function transferSharesFrom(
        PoolId poolId,
        ShareClassId scId,
        address sender,
        address from,
        address to,
        uint256 amount
    ) external payable;

    //----------------------------------------------------------------------------------------------
    // Bridging
    //----------------------------------------------------------------------------------------------

    /// @notice Transfers share class tokens to a cross-chain recipient address
    /// @dev To transfer to evm chains, pad a 20 byte evm address with 12 bytes of 0
    /// @param centrifugeId The destination chain id
    /// @param poolId The centrifuge pool id
    /// @param scId The share class id
    /// @param receiver A bytes32 representation of the receiver address
    /// @param sender The originator of the transfer; attributed in the event and forwarded to the
    ///        Hub-side bridging hook (e.g. the circuit breaker). A router/bridge passes the real user.
    ///        NOT authenticated here: it is attribution supplied by the (trusted) bridger or ward, so
    ///        hook authorizations keyed on it rely on that trust, not on a cryptographic identity.
    /// @param owner The account whose shares are transferred and burned; must hold the bridger role and be
    ///        the resolved sender unless the caller is a ward (e.g. a router bridging shares it pulled, or a
    ///        compatibility layer forwarding the original caller). Must have granted this contract
    ///        an ERC20 allowance for `amount` (optionally via permit); the shares are pulled with a standard
    ///        transferFrom so the flow works for share tokens without a force-transfer mechanism.
    /// @param amount The amount of tokens to transfer
    /// @param extraGasLimit Extra gas limit used for computation on the intermediary hub
    /// @param remoteExtraGasLimit Extra gas limit used for computation in the destination chain
    /// @param refund Address to refund the excess of the payment
    function crosschainTransferShares(
        uint16 centrifugeId,
        PoolId poolId,
        ShareClassId scId,
        bytes32 receiver,
        address sender,
        address owner,
        uint128 amount,
        uint128 extraGasLimit,
        uint128 remoteExtraGasLimit,
        address refund
    ) external payable;

    /// @notice Convenience overload for the caller bridging its own shares: `sender`, `owner`, and `refund`
    ///         default to the caller and `extraGasLimit` to 0.
    function crosschainTransferShares(
        uint16 centrifugeId,
        PoolId poolId,
        ShareClassId scId,
        bytes32 receiver,
        uint128 amount,
        uint128 remoteExtraGasLimit
    ) external payable;

    //----------------------------------------------------------------------------------------------
    // Requests & manager calls
    //----------------------------------------------------------------------------------------------

    /// @notice Initiates a spoke-direction manager call to a destination contract, routed through the Envoy
    ///         to the target's `IManagerCallFromSpoke.fromSpoke`.
    /// @param poolId The pool identifier
    /// @param target The destination target contract (as bytes32 for cross-chain compatibility)
    /// @param payload The action payload (any share class id is encoded here)
    /// @param extraGasLimit Additional gas for cross-chain execution
    /// @param refund Address to refund excess payment
    /// @dev Permissionless by choice, forwards caller's address to the target for permission validation
    function managerCall(PoolId poolId, bytes32 target, bytes calldata payload, uint128 extraGasLimit, address refund)
        external
        payable;

    //----------------------------------------------------------------------------------------------
    // View methods
    //----------------------------------------------------------------------------------------------

    /// @notice Stores pool, share class, asset, and price state for the spoke side
    function spokeRegistry() external view returns (ISpokeRegistry);

    /// @notice Dispatches cross-chain messages from this spoke to the hub chain
    function sender() external view returns (ISpokeMessageSender);

    /// @notice Stores the queued share and asset deltas pending submission to the hub
    function snapshotQueue() external view returns (ISnapshotQueue);

    /// @notice Returns the pool escrow provider
    function escrowProvider() external view returns (IEscrowProvider);

    /// @notice Returns the policy installed for a pool (address(0) if none)
    function policy(PoolId poolId) external view returns (IPolicy);

    /// @notice Returns the pool escrow.
    /// @dev    Assets for pending deposit requests are not held by the pool escrow.
    function escrow(PoolId poolId) external view returns (IEscrow);

    /// @notice Returns the amount of assets that can be withdrawn from the balance sheet.
    /// @dev    Assets that are locked (reserved) are not available for withdrawals.
    function availableBalanceOf(PoolId poolId, ShareClassId scId, address asset, uint256 tokenId)
        external
        view
        returns (uint128);
}

src/core/spoke/interfaces/ISpokeRegistry.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {IRegistrar} from "./IRegistrar.sol";
import {ISpokeRequestManager} from "./ISpokeRequestManager.sol";

import {D18} from "../../../misc/types/D18.sol";
import {IERC20} from "../../../misc/interfaces/IERC20.sol";

import {Price} from "../types/Price.sol";
import {PoolId} from "../../types/PoolId.sol";
import {AssetId} from "../../types/AssetId.sol";
import {ShareClassId} from "../../types/ShareClassId.sol";
import {IPolicy} from "../../utils/interfaces/IPolicy.sol";
import {IVaultFactory} from "../factories/interfaces/IVaultFactory.sol";

/// @dev Centrifuge pools
struct Pool {
    /// @dev Timestamp of pool creation
    uint64 createdAt;
}

/// @dev Each Centrifuge pool is associated to 1 or more share classes
struct ShareClassDetails {
    IERC20 shareToken;
    /// @dev The registrar that operates the share token (standard-specific driver)
    IRegistrar registrar;
    /// @dev Each share class has an individual price per share class unit in pool denomination (POOL_UNIT/SHARE_UNIT)
    Price pricePoolPerShare;
}

/// @dev Reverse lookup from a share token address to the pool and share class it backs
struct TokenDetails {
    PoolId poolId;
    ShareClassId scId;
}

struct AssetIdKey {
    /// @dev The address of the asset
    address asset;
    /// @dev The ERC6909 token id or 0, if the underlying asset is an ERC20
    uint256 tokenId;
}

struct VaultDetails {
    /// @dev PoolId the vault belongs to. The registry is the sole authority on this association: it is
    ///      recorded from the registering hub message, never read back from the vault
    PoolId poolId;
    /// @dev ShareClassId the vault belongs to, recorded alongside `poolId`
    ShareClassId scId;
    /// @dev AssetId of the asset
    AssetId assetId;
    /// @dev Address of the asset
    address asset;
    /// @dev TokenId of the asset - zero if asset is ERC20, non-zero if asset is ERC6909
    uint256 tokenId;
    /// @dev Whether the vault is linked to a share class atm
    bool isLinked;
}

/// @dev Packed into one slot so authorization-id computation reads the policy and its install
///      nonce with a single SLOAD.
struct PolicyInfo {
    IPolicy policy;
    uint64 nonce;
}

interface ISpokeRegistry {
    //----------------------------------------------------------------------------------------------
    // Events
    //----------------------------------------------------------------------------------------------

    event File(bytes32 indexed what, address data);
    event AddPool(PoolId indexed poolId);
    event SetPolicy(PoolId indexed poolId, IPolicy policy);
    /// @notice Emitted when a Hub-authorized, out-of-policy call is recorded (the Hub already ran the timelock,
    ///         so the spoke keeps no local one). `data` is the exact authorized calldata, so the action is
    ///         decodable straight from logs.
    event AuthorizationGranted(PoolId indexed poolId, bytes32 indexed authId, bytes data);
    /// @notice Emitted when the Hub revokes a not-yet-consumed authorization (decrements its counter).
    event AuthorizationRevoked(PoolId indexed poolId, bytes32 indexed authId, bytes data);
    /// @notice Emitted when a recorded authorization is consumed by an executing out-of-policy call.
    event AuthorizationConsumed(PoolId indexed poolId, address indexed caller, bytes32 indexed authId);
    event AddShareClass(PoolId indexed poolId, ShareClassId indexed scId, address token, IRegistrar registrar);
    event SetRequestManager(PoolId indexed poolId, ISpokeRequestManager manager);
    event UpdateManager(PoolId indexed poolId, address indexed who, bool canManage);
    event UpdateBridger(PoolId indexed poolId, address indexed who, bool canBridge);
    event UpdateAssetPrice(
        PoolId indexed poolId,
        ShareClassId indexed scId,
        address indexed asset,
        uint256 tokenId,
        D18 price,
        uint64 computedAt
    );
    event UpdateSharePrice(PoolId indexed poolId, ShareClassId indexed scId, D18 price, uint64 computedAt);
    event DeployVault(
        PoolId indexed poolId,
        ShareClassId indexed scId,
        address indexed asset,
        uint256 tokenId,
        IVaultFactory factory,
        address vault,
        bytes payload
    );
    event LinkVault(
        PoolId indexed poolId, ShareClassId indexed scId, address indexed asset, uint256 tokenId, address vault
    );
    event UnlinkVault(
        PoolId indexed poolId, ShareClassId indexed scId, address indexed asset, uint256 tokenId, address vault
    );

    //----------------------------------------------------------------------------------------------
    // Errors
    //----------------------------------------------------------------------------------------------

    error FileUnrecognizedParam();
    error PoolAlreadyAdded();
    error InvalidPool();
    error ShareClassAlreadyRegistered();
    error TokenAlreadyRegistered();
    error NotAContract();
    /// @notice Dispatched when a price is set with a `computedAt` ahead of this chain's clock. The
    ///         monotonic check below is what makes that permanent if allowed: a timestamp no later update
    ///         can match would wedge the entry for good, and nothing, Root included, can lower it again.
    ///         Mirrors the hub-side bound in ShareClassManager.updateSharePrice
    error CannotSetFuturePrice();
    error CannotSetOlderPrice();
    error UnknownAsset();
    error ShareTokenDoesNotExist();
    error InvalidPrice();
    error UnknownVault();
    error InvalidVault();
    error AlreadyLinkedVault();
    error AlreadyUnlinkedVault();
    error AlreadyRegisteredVault();
    /// @notice Dispatched when {authorize} targets a pool with no policy installed (nothing could consume it).
    error PolicyNotInstalled();
    /// @notice Dispatched when {consumeAuthorization} finds no recorded authorization for the call.
    error NoOutstandingAuthorization();
    /// @notice Dispatched when {consumeAuthorization} is called by anyone other than the pool's policy.
    error CallerNotPolicy();
    /// @notice Dispatched when {addShareClass}/{linkToken} pass a zero registrar, whose slot is the
    ///         share-class existence sentinel.
    error EmptyRegistrar();
    /// @notice Dispatched when {createAssetId} is called with a zero centrifugeId, whose raw ids would
    ///         collide with the ISO-4217 currency-reference encoding.
    error InvalidCentrifugeId();
    /// @notice Dispatched when {createAssetId} targets an (asset, tokenId) pair that already has an id.
    error AssetAlreadyRegistered();

    //----------------------------------------------------------------------------------------------
    // Setter methods
    //----------------------------------------------------------------------------------------------

    /// @notice Adds a new pool to the registry
    /// @param poolId The pool identifier
    function addPool(PoolId poolId) external;

    /// @notice Adds a share class to the registry
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param shareToken_ The share token address
    /// @param registrar_ The registrar that operates the share token
    function addShareClass(PoolId poolId, ShareClassId scId, address shareToken_, IRegistrar registrar_) external;

    /// @notice Links a share token and its registrar to a pool and share class, overwriting any existing link
    /// @dev Governance-only (not reachable from a hub message); used to attach a registrar to an existing token.
    ///      Requires an active pool; on a token swap the outgoing token's reverse lookup is retired, so
    ///      exactly one token resolves to the share class at any time
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param shareToken_ The share token address
    /// @param registrar_ The registrar that operates the share token
    function linkToken(PoolId poolId, ShareClassId scId, address shareToken_, IRegistrar registrar_) external;

    /// @notice Sets the request manager for a pool
    /// @param poolId The pool identifier
    /// @param manager The request manager contract
    function setRequestManager(PoolId poolId, ISpokeRequestManager manager) external;

    /// @notice Grants or revokes the pool manager role for an address
    /// @param poolId The pool identifier
    /// @param who The address whose role is updated
    /// @param canManage Whether the address is a manager
    function updateManager(PoolId poolId, address who, bool canManage) external;

    /// @notice Grants or revokes the bridger role for an address, gating cross-chain share transfers
    /// @param poolId The pool identifier
    /// @param who The address whose role is updated
    /// @param canBridge Whether the address is a bridger
    function updateBridger(PoolId poolId, address who, bool canBridge) external;

    /// @notice Record a Hub-authorized, out-of-policy call as immediately matured in the local ledger.
    ///         Auth-gated: only the message layer calls it, in response to a Hub {Authorize} message sent
    ///         after the Hub's timelock and veto window elapsed. A subsequent guarded call whose calldata
    ///         byte-matches `data` consumes it via the pool's policy.
    /// @dev A counter, not a flag, so several authorizations of the same call can be outstanding; each
    ///      matching call later consumes one.
    /// @param poolId The pool the authorized call targets
    /// @param data The exact calldata being authorized
    function authorize(PoolId poolId, bytes calldata data) external;

    /// @notice Revoke one outstanding, not-yet-consumed authorization for `data` (from a Hub {Unauthorize}
    ///         message). Auth-gated: only the message layer calls it. Reverts if none is recorded.
    /// @param poolId The pool the authorized call targets
    /// @param data The exact calldata whose authorization is revoked
    function unauthorize(PoolId poolId, bytes calldata data) external;

    /// @notice Install or replace the policy for a pool (address(0) to clear). Auth-gated.
    /// @dev    Bumps the pool's policy nonce, invalidating every outstanding authorization.
    function setPolicy(PoolId poolId, IPolicy policy) external;

    /// @notice Consume a recorded authorization for an executing out-of-policy call. Callable only by the
    ///         pool's installed policy (from its {IPolicy.enforce}). Reverts unless the call is authorized.
    /// @param poolId The pool the call targets
    /// @param caller The manager whose call is executing (for the audit event)
    /// @param data The exact calldata being executed
    function consumeAuthorization(PoolId poolId, address caller, bytes calldata data) external;

    /// @notice Returns the policy installed for a pool (address(0) if none).
    function policy(PoolId poolId) external view returns (IPolicy);

    /// @notice Incremented on every {setPolicy}. Part of the authorization-id namespace, so re-installing
    ///         a previously used policy address cannot resurrect authorizations from its earlier tenure.
    /// @param poolId The pool identifier
    function policyNonce(PoolId poolId) external view returns (uint64);

    /// @notice The identifier of an authorization for `data` on `poolId`, namespaced by the pool's
    ///         current policy and its install nonce, so any policy change (including re-installing
    ///         a previous policy address) invalidates all outstanding authorizations.
    function authId(PoolId poolId, bytes calldata data) external view returns (bytes32);

    /// @notice The number of Hub-authorized instances of a call currently recorded and awaiting consumption.
    function authorizations(bytes32 authId) external view returns (uint256 count);

    //----------------------------------------------------------------------------------------------
    // Vault management
    //----------------------------------------------------------------------------------------------

    /// @notice Records a vault in the registry. Each address may only be registered once with no
    ///         unregister path.
    function registerVault(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        address asset,
        uint256 tokenId,
        IVaultFactory factory,
        address vault,
        bytes calldata payload
    ) external;

    /// @notice Links a registered vault to the given pool, share class and asset
    function linkVault(PoolId poolId, ShareClassId scId, AssetId assetId, address vault) external;

    /// @notice Removes the link between a vault and the given pool, share class and asset
    function unlinkVault(PoolId poolId, ShareClassId scId, AssetId assetId, address vault) external;

    /// @notice Creates a new asset ID and registers the asset mapping in the registry
    /// @param centrifugeId The centrifuge chain ID
    /// @param asset The asset address
    /// @param tokenId The ERC6909 token id or 0 for ERC20
    /// @return assetId The new asset ID
    function createAssetId(uint16 centrifugeId, address asset, uint256 tokenId) external returns (AssetId assetId);

    /// @notice Updates the price per share for a given pool and share class
    /// @param poolId The pool id
    /// @param scId The share class id
    /// @param price The price of pool currency per share class token
    /// @param computedAt The timestamp when the price was computed
    function updatePricePoolPerShare(PoolId poolId, ShareClassId scId, D18 price, uint64 computedAt) external;

    /// @notice Updates the price per asset for a given pool, share class and asset
    /// @param poolId The pool id
    /// @param scId The share class id
    /// @param assetId The asset id
    /// @param price The price of pool currency per asset unit
    /// @param computedAt The timestamp when the price was computed
    function updatePricePoolPerAsset(PoolId poolId, ShareClassId scId, AssetId assetId, D18 price, uint64 computedAt)
        external;

    //----------------------------------------------------------------------------------------------
    // View methods
    //----------------------------------------------------------------------------------------------

    /// @notice Returns whether the given pool id is active
    /// @param poolId The pool id
    /// @return Whether the pool is active
    function isPoolActive(PoolId poolId) external view returns (bool);

    /// @notice Returns whether a share class is registered (has a share token) for the pool
    /// @param poolId The pool id
    /// @param scId The share class id
    /// @return Whether the share class exists
    function hasShareClass(PoolId poolId, ShareClassId scId) external view returns (bool);

    /// @notice Returns the share class token for a given pool and share class id
    /// @dev Returns the zero address if the share class does not exist; use {hasShareClass} to probe existence
    /// @param poolId The pool id
    /// @param scId The share class id
    /// @return The share token
    function shareToken(PoolId poolId, ShareClassId scId) external view returns (IERC20);

    /// @notice Returns both the share token and its registrar in a single call
    /// @dev Returns zero values if the share class does not exist. Avoids re-reading the share class twice when
    ///      a caller needs to operate the token through its registrar.
    /// @param poolId The pool id
    /// @param scId The share class id
    /// @return token The share token
    /// @return registrar_ The registrar operating the share token
    function shareTokenAndRegistrar(PoolId poolId, ShareClassId scId)
        external
        view
        returns (IERC20 token, IRegistrar registrar_);

    /// @notice Returns the pool and share class a given share token backs (zero values if unregistered)
    /// @dev A token backs at most one share class. Backed by public storage, so it never reverts; callers that
    ///      require the token to exist must check the returned poolId is not null.
    /// @param shareToken_ The share token address
    /// @return poolId The pool id the token backs
    /// @return scId The share class id the token backs
    function tokenDetails(address shareToken_) external view returns (PoolId poolId, ShareClassId scId);

    /// @notice Returns the asset address and tokenId associated with a given asset id (zero values if unregistered)
    /// @dev Non-reverting; use the `revertOnNull` overload (or {isRegistered}) to fail closed.
    /// @param assetId The underlying internal uint128 assetId.
    /// @return asset The address of the asset linked to the given asset id.
    /// @return tokenId The token id corresponding to the asset, i.e. zero if ERC20 or non-zero if ERC6909.
    function idToAsset(AssetId assetId) external view returns (address asset, uint256 tokenId);

    /// @notice Returns the asset address and tokenId associated with a given asset id.
    /// @param assetId The underlying internal uint128 assetId.
    /// @param revertOnNull If true, reverts {UnknownAsset} when the asset id is not registered.
    /// @return asset The address of the asset linked to the given asset id.
    /// @return tokenId The token id corresponding to the asset, i.e. zero if ERC20 or non-zero if ERC6909.
    function idToAsset(AssetId assetId, bool revertOnNull) external view returns (address asset, uint256 tokenId);

    /// @notice Returns the assetId for a given asset address and tokenId (null if unregistered)
    /// @dev Non-reverting; use the `revertOnNull` overload (or {isRegistered}) to fail closed.
    /// @param asset The address of the asset linked to the given asset id.
    /// @param tokenId The token id corresponding to the asset, i.e. zero if ERC20 or non-zero if ERC6909.
    /// @return assetId The underlying internal uint128 assetId.
    function assetToId(address asset, uint256 tokenId) external view returns (AssetId assetId);

    /// @notice Returns the assetId for a given asset address and tokenId.
    /// @param asset The address of the asset linked to the given asset id.
    /// @param tokenId The token id corresponding to the asset, i.e. zero if ERC20 or non-zero if ERC6909.
    /// @param revertOnNull If true, reverts {UnknownAsset} when the asset is not registered.
    /// @return assetId The underlying internal uint128 assetId.
    function assetToId(address asset, uint256 tokenId, bool revertOnNull) external view returns (AssetId assetId);

    /// @notice Returns whether an asset id is registered
    /// @param assetId The underlying internal uint128 assetId.
    /// @return Whether the asset id is registered
    function isRegistered(AssetId assetId) external view returns (bool);

    /// @notice Returns the price per share for a given pool and share class
    /// @param poolId The pool id
    /// @param scId The share class id
    /// @param checkValidity Whether to check if the price is valid
    /// @return price The pool price per share
    function pricePoolPerShare(PoolId poolId, ShareClassId scId, bool checkValidity) external view returns (D18 price);

    /// @notice Returns the price per asset for a given pool, share class and asset
    /// @param poolId The pool id
    /// @param scId The share class id
    /// @param assetId The asset id
    /// @param checkValidity Whether to check if the price is valid
    /// @return price The pool price per asset unit
    function pricePoolPerAsset(PoolId poolId, ShareClassId scId, AssetId assetId, bool checkValidity)
        external
        view
        returns (D18 price);

    /// @notice Returns the timestamp at which the share price was last computed (0 if never)
    /// @param poolId The pool id
    /// @param scId The share class id
    function pricePoolPerShareComputedAt(PoolId poolId, ShareClassId scId) external view returns (uint64 computedAt);

    /// @notice Returns the timestamp at which the asset price was last computed (0 if never)
    /// @param poolId The pool id
    /// @param scId The share class id
    /// @param assetId The asset id
    function pricePoolPerAssetComputedAt(PoolId poolId, ShareClassId scId, AssetId assetId)
        external
        view
        returns (uint64 computedAt);

    /// @notice Returns the request manager for a given pool
    /// @param poolId The pool id
    /// @return manager The request manager for the pool
    function requestManager(PoolId poolId) external view returns (ISpokeRequestManager manager);

    /// @notice Returns whether an address holds the pool manager role
    function manager(PoolId poolId, address who) external view returns (bool);

    /// @notice Returns whether an address holds the bridger role for a pool
    function bridger(PoolId poolId, address who) external view returns (bool);

    /// @notice Returns whether a vault has been registered (regardless of its link state)
    function isVaultRegistered(address vault) external view returns (bool);

    /// @notice Returns the details of a vault
    /// @dev Returns a zeroed struct if the vault is not registered; use {isVaultRegistered} to probe existence
    function vaultDetails(address vault) external view returns (VaultDetails memory details);

    /// @notice Checks whether a given vault is linked to a share class
    function isLinked(address vault) external view returns (bool);
}

src/core/spoke/interfaces/ISpokeRequestManager.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {PoolId} from "../../types/PoolId.sol";
import {AssetId} from "../../types/AssetId.sol";
import {ShareClassId} from "../../types/ShareClassId.sol";

interface ISpokeRequestManager {
    //----------------------------------------------------------------------------------------------
    // Errors
    //----------------------------------------------------------------------------------------------

    error UnknownRequestCallbackType();

    //----------------------------------------------------------------------------------------------
    // Request handling
    //----------------------------------------------------------------------------------------------

    /// @notice Handles a request callback originating from the Hub side
    /// @param poolId The pool id
    /// @param scId The share class id
    /// @param assetId The asset id
    /// @param payload The payload to be processed by the request callback
    function callback(PoolId poolId, ShareClassId scId, AssetId assetId, bytes calldata payload) external;
}

src/core/spoke/types/Price.sol

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

import {D18} from "../../../misc/types/D18.sol";

/// @dev Price struct that contains a price and the timestamp at which it was computed.
struct Price {
    D18 price;
    uint64 computedAt;
}

/// @dev Checks if a price is valid. Prices do not expire in core; a price is valid once it has been
/// computed (computedAt != 0).
function isValid(Price memory price) pure returns (bool) {
    return price.computedAt != 0;
}

using {isValid} for Price global;

src/core/types/AssetId.sol

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

/// @dev Composite Id of the centrifugeId (uint16) where the asset resides
///      and a local counter (uint64) that is part of the contract that registers the asset.
type AssetId is uint128;

function isNull(AssetId assetId) pure returns (bool) {
    return AssetId.unwrap(assetId) == 0;
}

function raw(AssetId assetId) pure returns (uint128) {
    return AssetId.unwrap(assetId);
}

function centrifugeId(AssetId assetId) pure returns (uint16) {
    return uint16(AssetId.unwrap(assetId) >> 112);
}

function newAssetId(uint16 centrifugeId_, uint64 counter) pure returns (AssetId) {
    return AssetId.wrap((uint128(centrifugeId_) << 112) + counter);
}

function newAssetId(uint32 isoCode) pure returns (AssetId) {
    return AssetId.wrap(isoCode);
}

function eq(AssetId a, AssetId b) pure returns (bool) {
    return a.raw() == b.raw();
}

using {isNull, raw, centrifugeId, eq as ==} for AssetId global;

src/core/types/PoolId.sol

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

type PoolId is uint64;

function centrifugeId(PoolId poolId) pure returns (uint16) {
    return uint16(PoolId.unwrap(poolId) >> 48);
}

function newPoolId(uint16 centrifugeId_, uint48 localPoolId) pure returns (PoolId) {
    return PoolId.wrap((uint64(centrifugeId_) << 48) | uint64(localPoolId));
}

function isNull(PoolId poolId) pure returns (bool) {
    return PoolId.unwrap(poolId) == 0;
}

function isEqual(PoolId a, PoolId b) pure returns (bool) {
    return PoolId.unwrap(a) == PoolId.unwrap(b);
}

function raw(PoolId poolId) pure returns (uint64) {
    return PoolId.unwrap(poolId);
}

using {centrifugeId, isNull, raw, isEqual as ==} for PoolId global;

src/core/types/ShareClassId.sol

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

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

type ShareClassId is bytes16;

function isNull(ShareClassId scId) pure returns (bool) {
    return ShareClassId.unwrap(scId) == 0;
}

function index(ShareClassId scId) pure returns (uint32) {
    return uint32(uint128(ShareClassId.unwrap(scId)));
}

function equals(ShareClassId left, ShareClassId right) pure returns (bool) {
    return ShareClassId.unwrap(left) == ShareClassId.unwrap(right);
}

function raw(ShareClassId scId) pure returns (bytes16) {
    return ShareClassId.unwrap(scId);
}

function newShareClassId(PoolId poolId, uint32 index_) pure returns (ShareClassId scId) {
    return ShareClassId.wrap(bytes16((uint128(PoolId.unwrap(poolId)) << 64) + index_));
}

using {isNull, index, raw, equals as ==} for ShareClassId global;

src/core/utils/interfaces/IBatchedMulticall.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {IGateway} from "../../messaging/interfaces/IGateway.sol";

/// @notice A multicall that batches the messages using the gateway
interface IBatchedMulticall {
    error AlreadyBatching();

    /// @notice Returns the gateway contract used for batching messages
    /// @return The gateway contract instance
    function gateway() external view returns (IGateway);
}

src/core/utils/interfaces/IManagerCall.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {PoolId} from "../../types/PoolId.sol";

/// @notice Hub-direction target surface for the payable `ManagerCall` path. Pool-scoped: any `scId` is
///         encoded in `payload`. Targets are reached through the `Envoy` (never the Hub, which redeploys).
/// @dev    Intentionally distinct from {IManagerCallFromSpoke}: distinct method names = distinct selectors,
///         so `Envoy.callFromSpoke` reverts on any hub-only target that implements `fromHub` only — that
///         selector mismatch is the direction boundary; do not collapse the two interfaces. `payable` is
///         required for value forwarding. The signature is final: the `Envoy` holds it across releases and
///         must never redeploy. No origin `(centrifugeId, sender)`: the call is already authorized at the
///         Hub (`_enforce` + policy) and the origin is always the hub's own chain.
interface IManagerCallFromHub {
    /// @notice Triggers a policy-supervised manager action. Caller MUST be the `Envoy`.
    /// @dev    Authorization is enforced at `Hub.managerCall` -> `_enforce` -> policy before this runs.
    ///         Value (if any) funds downstream messages.
    /// @param  poolId The pool the call is scoped to
    /// @param  payload Action-specific encoding decoded by the target
    function fromHub(PoolId poolId, bytes calldata payload) external payable;
}

/// @notice Spoke-direction target surface for the payable `ManagerCall` path. Reached via the
///         `ManagerCallFromSpoke` message -> `Envoy.callFromSpoke`. Bypasses the Hub's policy check by
///         construction, so the target MUST validate `(centrifugeId, sender)`.
/// @dev    Implemented by e.g. `OracleValuation` for feeder-validated remote price updates.
///         Distinct from {IManagerCallFromHub} — that split is the direction boundary; do not collapse them.
interface IManagerCallFromSpoke {
    /// @notice Triggers a manager action on a spoke-direction target. Caller MUST be the `Envoy`.
    /// @dev    Untrusted: bypasses the pool's policy. The target MUST validate `(centrifugeId, sender)`.
    ///         Value (if any) funds downstream messages.
    /// @param  poolId The pool the call is scoped to
    /// @param  payload Action-specific encoding decoded by the target
    /// @param  centrifugeId Origin chain of the caller
    /// @param  sender The originating actor (the spoke-side caller)
    function fromSpoke(PoolId poolId, bytes calldata payload, uint16 centrifugeId, bytes32 sender) external payable;
}

src/core/utils/interfaces/IPolicy.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {PoolId} from "../../types/PoolId.sol";

/// @notice A pool's policy hook. Its enforcer calls {enforce} on every guarded call: the Hub on guarded
///         manager methods, the Spoke on guarded spoke calls. The policy itself holds no authorization
///         state. The ledger that stores, matures, vetoes and consumes authorizations lives in the enforcer's
///         registry ({IHubRegistry} on the Hub, {ISpokeRegistry} on the Spoke), so every policy shares one
///         audited, observable ledger.
/// @dev    How a call is classified is role-specific and lives in the subtypes: the Hub prices a delay
///         ({IHubPolicy}), the Spoke answers yes/no ({ISpokePolicy}). Zero and `false` both mean "in
///         policy". The two are intentionally distinct method names, so their selectors and interface ids
///         differ and neither can be read through the other's ABI; do not collapse them.
interface IPolicy {
    /// @notice Dispatched when {enforce} is called by anyone other than the enforcer (the Hub or Spoke this
    ///         policy is installed on).
    error NotEnforcer();

    /// @notice Enforce the pool's policy on a call. Callable only by the enforcer (the Hub or Spoke). No-op
    ///         when the call is in policy; otherwise consumes a matured authorization from the enforcer's
    ///         registry ledger, reverting if none exists.
    /// @param poolId The pool being operated on.
    /// @param caller The manager that initiated the call.
    /// @param data The call's calldata.
    function enforce(PoolId poolId, address caller, bytes calldata data) external;
}

/// @notice Hub-side policy. The Hub times a delay before an out-of-policy authorization can execute, so
///         classification returns that delay.
interface IHubPolicy is IPolicy {
    /// @notice Classify a call against the policy, returning the delay an authorization must age.
    /// @return delay 0 if the call is in policy (runs synchronously); otherwise the duration an
    ///         authorization for this call must age before it can execute. Reverts outright to block a
    ///         forbidden call (so it can't even be authorized).
    /// @param poolId The pool being operated on.
    /// @param caller The manager initiating the call.
    /// @param data The call's calldata.
    function authorizationDelay(PoolId poolId, address caller, bytes calldata data) external view returns (uint48 delay);
}

/// @notice Spoke-side policy. The Spoke has no local timelock — authorizations arrive already matured from the
///         Hub and are consumed from a counter ledger — so its policy decision is binary.
/// @dev    Unlike {IHubPolicy.authorizationDelay} (which the Hub calls to price the delay), the Spoke
///         enforcer never calls {authorizationRequired}: the in/out-of-policy decision lives inside {enforce}.
///         It is exposed purely for external consumers — off-chain tooling, monitoring, and UIs — to preview a
///         call's policy without sending it. It is therefore optional: a spoke policy need only implement
///         {IPolicy.enforce}, and implementing this interface is a convenience for exposing that preview in a
///         typed form.
interface ISpokePolicy is IPolicy {
    /// @notice Preview whether a call requires a matured authorization. Not called by the Spoke enforcer;
    ///         provided for off-chain and other external consumers.
    /// @return required true if the call requires a matured authorization consumed from the spoke ledger;
    ///         false if it runs synchronously (in policy). Reverts outright to block a forbidden call.
    /// @param poolId The pool being operated on.
    /// @param caller The manager initiating the call.
    /// @param data The call's calldata.
    function authorizationRequired(PoolId poolId, address caller, bytes calldata data)
        external
        view
        returns (bool required);
}

src/misc/Auth.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

import {IAuth} from "./interfaces/IAuth.sol";

/// @title  Auth
/// @notice Simple authentication pattern
/// @author Based on code from https://github.com/makerdao/dss
abstract contract Auth is IAuth {
    /// @inheritdoc IAuth
    mapping(address => uint256) public wards;

    constructor(address initialWard) {
        wards[initialWard] = 1;
        emit Rely(initialWard);
    }

    /// @dev Check if the msg.sender has permissions
    modifier auth() {
        require(wards[msg.sender] == 1, NotAuthorized());
        _;
    }

    /// @inheritdoc IAuth
    function rely(address user) public auth {
        wards[user] = 1;
        emit Rely(user);
    }

    /// @inheritdoc IAuth
    function deny(address user) public auth {
        wards[user] = 0;
        emit Deny(user);
    }
}

src/misc/Multicall.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;

// NOTE: This file has warning disabled due https://github.com/ethereum/solidity/issues/14359
// If perform any change on it, please ensure no other warnings appears

import {IMulticall} from "./interfaces/IMulticall.sol";
import {ReentrancyProtection} from "./ReentrancyProtection.sol";

/// @title  Multicall
/// @notice Abstract contract that enables batch execution of multiple function calls in a single transaction.
abstract contract Multicall is ReentrancyProtection, IMulticall {
    function multicall(bytes[] calldata data) public payable virtual protected {
        uint256 totalBytes = data.length;
        for (uint256 i; i < totalBytes; ++i) {
            (bool success, bytes memory returnData) = address(this).delegatecall(data[i]);
            if (!success) {
                uint256 length = returnData.length;
                require(length != 0, CallFailedWithEmptyRevert());

                assembly ("memory-safe") {
                    revert(add(32, returnData), length)
                }
            }
        }
    }
}

src/misc/Recoverable.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

import {Auth} from "./Auth.sol";
import {SafeTransferLib} from "./libraries/SafeTransferLib.sol";
import {IERC6909, TransferFailed} from "./interfaces/IERC6909.sol";
import {IRecoverable, ETH_ADDRESS} from "./interfaces/IRecoverable.sol";

/// @title  Recoverable
/// @notice Abstract contract that provides emergency token recovery functionality, allowing authorized parties
///         to retrieve accidentally sent ETH, ERC20, or ERC6909 tokens from the contract to a specified
///         receiver address.
abstract contract Recoverable is Auth, IRecoverable {
    /// @inheritdoc IRecoverable
    function recoverTokens(address token, address receiver, uint256 amount) public auth {
        if (token == ETH_ADDRESS) {
            SafeTransferLib.safeTransferETH(receiver, amount);
        } else {
            SafeTransferLib.safeTransfer(token, receiver, amount);
        }
    }

    /// @inheritdoc IRecoverable
    function recoverTokens(address token, uint256 tokenId, address receiver, uint256 amount) external auth {
        if (tokenId == 0) {
            recoverTokens(token, receiver, amount);
        } else {
            require(IERC6909(token).transfer(receiver, tokenId, amount), TransferFailed());
        }
    }
}

src/misc/ReentrancyProtection.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;

// NOTE: This file has warning disabled due https://github.com/ethereum/solidity/issues/14359
// If perform any change on it, please ensure no other warnings appears

/// @title  ReentrancyProtection
/// @notice Abstract contract that implements reentrancy protection using transient storage.
abstract contract ReentrancyProtection {
    /// @notice Dispatched when there is a re-entrancy issue
    error UnauthorizedSender();

    address private transient _initiator;

    /// @dev The method is protected for reentrancy issues.
    modifier protected() {
        if (_initiator == address(0)) {
            // Single call re-entrancy lock
            _initiator = msg.sender;
            _;
            _initiator = address(0);
        } else {
            // Multicall re-entrancy lock
            require(msg.sender == _initiator, UnauthorizedSender());
            _;
        }
    }
}

src/misc/interfaces/IAuth.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

interface IAuth {
    event Rely(address indexed user);
    event Deny(address indexed user);

    error NotAuthorized();

    /// @notice Returns whether the target is a ward (has admin access)
    /// @param target The address to check for ward status
    /// @return The ward status (1 if ward, 0 if not)
    function wards(address target) external view returns (uint256);

    /// @notice Make user a ward (give them admin access)
    /// @param user The address to grant ward status to
    function rely(address user) external;

    /// @notice Remove user as a ward (remove admin access)
    /// @param user The address to remove ward status from
    function deny(address user) external;
}

src/misc/interfaces/IERC1404.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

interface IERC1404 {
    /// @notice Detects if a transfer will be reverted and if so returns an appropriate reference code
    /// @param from Sending address
    /// @param to Receiving address
    /// @param value Amount of tokens being transferred
    /// @return Code by which to reference message for rejection reasoning
    /// @dev Overwrite with your custom transfer restriction logic
    function detectTransferRestriction(address from, address to, uint256 value) external view returns (uint8);

    /// @notice Returns a human-readable message for a given restriction code
    /// @param restrictionCode Identifier for looking up a message
    /// @return Text showing the restriction's reasoning
    /// @dev Overwrite with your custom message and restrictionCode handling
    function messageForTransferRestriction(uint8 restrictionCode) external view returns (string memory);
}

src/misc/interfaces/IERC165.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

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

src/misc/interfaces/IERC20.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title  IERC20
/// @dev    Interface of the ERC20 standard as defined in the EIP.
/// @author Modified from OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
interface IERC20 {
    error InvalidAddress();
    error InsufficientBalance();
    error InsufficientAllowance();

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

/**
 * @dev Interface for the optional metadata functions from the ERC20 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);
}

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    error PermitExpired();
    error InvalidPermit();

    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
        external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

interface IERC20Wrapper {
    /**
     * @dev Returns the address of the underlying ERC-20 token that is being wrapped.
     */
    function underlying() external view returns (address);

    /**
     * @dev Allow a user to deposit underlying tokens and mint the corresponding number of wrapped tokens.
     */
    function depositFor(address account, uint256 value) external returns (bool);

    /**
     * @dev Allow a user to burn a number of wrapped tokens and withdraw the corresponding number of underlying tokens.
     */
    function withdrawTo(address account, uint256 value) external returns (bool);
}

src/misc/interfaces/IERC6909.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {IERC165} from "forge-std/interfaces/IERC165.sol";

/// @notice Dispatched when an ERC-6909 transfer returns false instead of reverting.
error TransferFailed();

interface IERC6909 is IERC165 {
    error EmptyOwner();
    error EmptyAmount();
    error InvalidTokenId();
    error InsufficientBalance(address owner, uint256 tokenId);
    error InsufficientAllowance(address sender, uint256 tokenId);

    event OperatorSet(address indexed owner, address indexed operator, bool approved);
    event Approval(address indexed owner, address indexed spender, uint256 indexed tokenId, uint256 amount);
    event Transfer(address caller, address indexed from, address indexed to, uint256 indexed tokenId, uint256 amount);

    /// @notice           Owner balance of a tokenId.
    /// @param owner      The address of the owner.
    /// @param tokenId    The id of the token.
    /// @return amount    The balance of the token.
    function balanceOf(address owner, uint256 tokenId) external view returns (uint256 amount);

    /// @notice           Spender allowance of a tokenId.
    /// @param owner      The address of the owner.
    /// @param spender    The address of the spender.
    /// @param tokenId    The id of the token.
    /// @return amount    The allowance of the token.
    function allowance(address owner, address spender, uint256 tokenId) external view returns (uint256 amount);

    /// @notice           Checks if a spender is approved by an owner as an operator.
    /// @param owner      The address of the owner.
    /// @param spender    The address of the spender.
    /// @return approved  The approval status.
    function isOperator(address owner, address spender) external view returns (bool approved);

    /// @notice           Transfers an amount of a tokenId from the caller to a receiver.
    /// @param receiver   The address of the receiver.
    /// @param tokenId    The id of the token.
    /// @param amount     The amount of the token.
    /// @return bool      True, always, unless the function reverts.
    function transfer(address receiver, uint256 tokenId, uint256 amount) external returns (bool);

    /// @notice           Transfers an amount of a tokenId from a sender to a receiver.
    /// @param sender     The address of the sender.
    /// @param receiver   The address of the receiver.
    /// @param tokenId    The id of the token.
    /// @param amount     The amount of the token.
    /// @return bool      True, always, unless the function reverts.
    function transferFrom(address sender, address receiver, uint256 tokenId, uint256 amount) external returns (bool);

    /// @notice           Approves an amount of a tokenId to a spender.
    /// @param spender    The address of the spender.
    /// @param tokenId    The id of the token.
    /// @param amount     The amount of the token.
    /// @return bool      True, always.
    function approve(address spender, uint256 tokenId, uint256 amount) external returns (bool);

    /// @notice           Sets or removes an operator for the caller.
    /// @param operator   The address of the operator.
    /// @param approved   The approval status.
    /// @return bool      True, always.
    function setOperator(address operator, bool approved) external returns (bool);
}

interface IERC6909URIExt {
    event TokenURISet(uint256 indexed tokenId, string uri);
    event ContractURISet(address indexed target, string uri);

    error EmptyURI();

    /// @return uri     Returns the common token URI.
    function contractURI() external view returns (string memory);

    /// @dev            Returns empty string if tokenId does not exist.
    ///                 MAY implemented to throw MissingURI(tokenId) error.
    /// @param tokenId  The token to query URI for.
    /// @return uri     A string representing the uri for the specific tokenId.
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

interface IERC6909NFT is IERC6909, IERC6909URIExt {
    error UnknownTokenId(address owner, uint256 tokenId);
    error LessThanMinimalDecimal(uint8 minimal, uint8 actual);

    /// @notice             Provide URI for a specific tokenId.
    /// @param tokenId      Token Id.
    /// @param URI          URI to a document defining the collection as a whole.
    function setTokenURI(uint256 tokenId, string memory URI) external;

    /// @dev                Optional method to set up the contract URI if needed.
    /// @param URI          URI to a document defining the collection as a whole.
    function setContractURI(string memory URI) external;

    /// @notice             Mint new tokens for a given owner and sets tokenURI.
    /// @dev                For non-fungible tokens, call with amount = 1, for fungible it could be any amount.
    ///                     TokenId is auto incremented by one.
    ///
    /// @param owner        Creates supply of a given tokenId by amount for owner.
    /// @param tokenURI     URI fortestBurningToken the newly minted token.
    /// @return tokenId     Id of the newly minted token.
    function mint(address owner, string memory tokenURI) external returns (uint256 tokenId);

    /// @notice             Destroy supply of a given tokenId by amount.
    /// @dev                The msg.sender MUST be the owner.
    ///
    /// @param tokenId      Item which have reduced supply.
    function burn(uint256 tokenId) external;
}

/// @notice Extension of ERC6909 Standard for tracking total supply
interface IERC6909TotalSupplyExt {
    /// @notice         The totalSupply for a token id.
    ///
    /// @param tokenId  Id of the token
    /// @return supply  Total supply for a given `tokenId`
    function totalSupply(uint256 tokenId) external returns (uint256 supply);
}

interface IERC6909Decimals {
    /// @notice             Used to retrieve the decimals of an asset
    /// @dev                address is used but the value corresponds to a AssetId
    function decimals(uint256 assetId) external view returns (uint8);
}

interface IERC6909MetadataExt is IERC6909Decimals {
    /// @notice             Used to retrieve the decimals of an asset
    /// @dev                address is used but the value corresponds to a AssetId
    function decimals(uint256 assetId) external view returns (uint8);

    /// @notice             Used to retrieve the name of an asset
    /// @dev                address is used but the value corresponds to a AssetId
    function name(uint256 assetId) external view returns (string memory);

    /// @notice             Used to retrieve the symbol of an asset
    /// @dev                address is used but the value corresponds to a AssetId
    function symbol(uint256 assetId) external view returns (string memory);
}

/// @notice Subset of ERC-6909 that omits the operator pattern (isOperator, setOperator, OperatorSet).
interface IERC6909ExclOperator {
    error EmptyOwner();
    error EmptyAmount();
    error InvalidTokenId();
    error InsufficientBalance(address owner, uint256 tokenId);
    error InsufficientAllowance(address sender, uint256 tokenId);

    event Approval(address indexed owner, address indexed spender, uint256 indexed tokenId, uint256 amount);
    event Transfer(address caller, address indexed from, address indexed to, uint256 indexed tokenId, uint256 amount);

    function balanceOf(address owner, uint256 tokenId) external view returns (uint256 amount);
    function allowance(address owner, address spender, uint256 tokenId) external view returns (uint256 amount);
    function transfer(address receiver, uint256 tokenId, uint256 amount) external returns (bool);
    function transferFrom(address sender, address receiver, uint256 tokenId, uint256 amount) external returns (bool);
    function approve(address spender, uint256 tokenId, uint256 amount) external returns (bool);
}

interface IERC6909Fungible is IERC6909 {
    /// @notice             Mint new tokens for a specific tokenid and assign them to an owner
    ///
    /// @param owner        Creates supply of a given `tokenId` by `amount` for owner.
    /// @param tokenId      Id of the item
    /// @param amount       Adds `amount` to the total supply of the given `tokenId`
    function mint(address owner, uint256 tokenId, uint256 amount) external;

    /// @notice             Destroy supply of a given tokenId by amount.
    /// @dev                The msg.sender MUST be the owner.
    ///
    /// @param owner        Owner of the `tokenId`
    /// @param tokenId      Id of the item.
    /// @param amount       Subtract `amount` from the total supply of the given `tokenId`
    function burn(address owner, uint256 tokenId, uint256 amount) external;
}

/// @dev  A factory contract to deploy new collateral contracts implementing IERC6909.
interface IERC6909Factory {
    /// Events
    event NewTokenDeployment(address indexed owner, address instance);

    /// @notice       Deploys new install of a contract that implements IERC6909.
    /// @dev          Factory should deploy deterministically if possible.
    ///
    /// @param owner  Owner of the deployed collateral contract which has initial full rights.
    /// @param salt   Used to make a deterministic deployment.
    /// @return       An address of the newly deployed contract.
    function deploy(address owner, bytes32 salt) external returns (address);

    /// @notice       Generates a new deterministic address based on the owner and the salt.
    ///
    /// @param owner  Owner of the deployed collateral contract which has initial full rights.
    /// @param salt   Used to make a deterministic deployment.
    /// @return       An address of the newly deployed contract.
    function previewAddress(address owner, bytes32 salt) external returns (address);
}

src/misc/interfaces/IERC7540.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

interface IERC7540Operator {
    /**
     * @dev The event emitted when an operator is set.
     *
     * @param controller The address of the controller.
     * @param operator The address of the operator.
     * @param approved The approval status.
     */
    event OperatorSet(address indexed controller, address indexed operator, bool approved);

    /**
     * @dev Sets or removes an operator for the caller.
     *
     * @param operator The address of the operator.
     * @param approved The approval status.
     * @return Whether the call was executed successfully or not
     */
    function setOperator(address operator, bool approved) external returns (bool);

    /**
     * @dev Returns `true` if the `operator` is approved as an operator for an `controller`.
     *
     * @param controller The address of the controller.
     * @param operator The address of the operator.
     * @return status The approval status
     */
    function isOperator(address controller, address operator) external view returns (bool status);
}

interface IERC7540Deposit is IERC7540Operator {
    event DepositRequest(
        address indexed controller, address indexed owner, uint256 indexed requestId, address sender, uint256 assets
    );
    /**
     * @dev Transfers assets from sender into the Vault and submits a Request for asynchronous deposit.
     *
     * - MUST support ERC-20 approve / transferFrom on asset as a deposit Request flow.
     * - MUST revert if all of assets cannot be requested for deposit.
     * - owner MUST be msg.sender unless some unspecified explicit approval is given by the caller,
     *    approval of ERC-20 tokens from owner to sender is NOT enough.
     *
     * @param assets the amount of deposit assets to transfer from owner
     * @param controller the controller of the request who will be able to operate the request
     * @param owner the source of the deposit assets
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault's underlying asset token.
     */

    function requestDeposit(uint256 assets, address controller, address owner) external returns (uint256 requestId);

    /**
     * @dev Returns the amount of requested assets in Pending state.
     *
     * - MUST NOT include any assets in Claimable state for deposit or mint.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT revert unless due to integer overflow caused by an unreasonably large input.
     */
    function pendingDepositRequest(uint256 requestId, address controller) external view returns (uint256 pendingAssets);

    /**
     * @dev Returns the amount of requested assets in Claimable state for the controller to deposit or mint.
     *
     * - MUST NOT include any assets in Pending state.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT revert unless due to integer overflow caused by an unreasonably large input.
     */
    function claimableDepositRequest(uint256 requestId, address controller)
        external
        view
        returns (uint256 claimableAssets);

    /**
     * @dev Mints shares Vault shares to receiver by claiming the Request of the controller.
     *
     * - MUST emit the Deposit event.
     * - controller MUST equal msg.sender unless the controller has approved the msg.sender as an operator.
     */
    function deposit(uint256 assets, address receiver, address controller) external returns (uint256 shares);

    /**
     * @dev Mints exactly shares Vault shares to receiver by claiming the Request of the controller.
     *
     * - MUST emit the Deposit event.
     * - controller MUST equal msg.sender unless the controller has approved the msg.sender as an operator.
     */
    function mint(uint256 shares, address receiver, address controller) external returns (uint256 assets);
}

interface IERC7540Redeem is IERC7540Operator {
    event RedeemRequest(
        address indexed controller, address indexed owner, uint256 indexed requestId, address sender, uint256 shares
    );

    /**
     * @dev Assumes control of shares from sender into the Vault and submits a Request for asynchronous redeem.
     *
     * - MUST support a redeem Request flow where the control of shares is taken from sender directly
     *   where msg.sender has ERC-20 approval over the shares of owner.
     * - MUST revert if all of shares cannot be requested for redeem.
     *
     * @param shares the amount of shares to be redeemed to transfer from owner
     * @param controller the controller of the request who will be able to operate the request
     * @param owner the source of the shares to be redeemed
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault's share token.
     */
    function requestRedeem(uint256 shares, address controller, address owner) external returns (uint256 requestId);

    /**
     * @dev Returns the amount of requested shares in Pending state.
     *
     * - MUST NOT include any shares in Claimable state for redeem or withdraw.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT revert unless due to integer overflow caused by an unreasonably large input.
     */
    function pendingRedeemRequest(uint256 requestId, address controller) external view returns (uint256 pendingShares);

    /**
     * @dev Returns the amount of requested shares in Claimable state for the controller to redeem or withdraw.
     *
     * - MUST NOT include any shares in Pending state for redeem or withdraw.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT revert unless due to integer overflow caused by an unreasonably large input.
     */
    function claimableRedeemRequest(uint256 requestId, address controller)
        external
        view
        returns (uint256 claimableShares);
}

interface IERC7887Deposit {
    event CancelDepositRequest(address indexed controller, uint256 indexed requestId, address sender);
    event CancelDepositClaim(
        address indexed controller, address indexed receiver, uint256 indexed requestId, address sender, uint256 assets
    );

    /**
     * @dev Submits a Request for cancelling the pending deposit Request
     *
     * - controller MUST be msg.sender unless some unspecified explicit approval is given by the caller,
     *    approval of ERC-20 tokens from controller to sender is NOT enough.
     * - MUST set pendingCancelDepositRequest to `true` for the returned requestId after request
     * - MUST increase claimableCancelDepositRequest for the returned requestId after fulfillment
     * - SHOULD be claimable using `claimCancelDepositRequest`
     * Note: while `pendingCancelDepositRequest` is `true`, `requestDeposit` cannot be called
     */
    function cancelDepositRequest(uint256 requestId, address controller) external;

    /**
     * @dev Returns whether the deposit Request is pending cancellation
     *
     * - MUST NOT show any variations depending on the caller.
     */
    function pendingCancelDepositRequest(uint256 requestId, address controller) external view returns (bool isPending);

    /**
     * @dev Returns the amount of assets that were canceled from a deposit Request, and can now be claimed.
     *
     * - MUST NOT show any variations depending on the caller.
     */
    function claimableCancelDepositRequest(uint256 requestId, address controller)
        external
        view
        returns (uint256 claimableAssets);

    /**
     * @dev Claims the canceled deposit assets, and removes the pending cancellation Request
     *
     * - controller MUST be msg.sender unless some unspecified explicit approval is given by the caller,
     *    approval of ERC-20 tokens from controller to sender is NOT enough.
     * - MUST set pendingCancelDepositRequest to `false` for the returned requestId after request
     * - MUST set claimableCancelDepositRequest to 0 for the returned requestId after fulfillment
     */
    function claimCancelDepositRequest(uint256 requestId, address receiver, address controller)
        external
        returns (uint256 assets);
}

interface IERC7887Redeem {
    event CancelRedeemRequest(address indexed controller, uint256 indexed requestId, address sender);
    event CancelRedeemClaim(
        address indexed controller, address indexed receiver, uint256 indexed requestId, address sender, uint256 shares
    );

    /**
     * @dev Submits a Request for cancelling the pending redeem Request
     *
     * - controller MUST be msg.sender unless some unspecified explicit approval is given by the caller,
     *    approval of ERC-20 tokens from controller to sender is NOT enough.
     * - MUST set pendingCancelRedeemRequest to `true` for the returned requestId after request
     * - MUST increase claimableCancelRedeemRequest for the returned requestId after fulfillment
     * - SHOULD be claimable using `claimCancelRedeemRequest`
     * Note: while `pendingCancelRedeemRequest` is `true`, `requestRedeem` cannot be called
     */
    function cancelRedeemRequest(uint256 requestId, address controller) external;

    /**
     * @dev Returns whether the redeem Request is pending cancellation
     *
     * - MUST NOT show any variations depending on the caller.
     */
    function pendingCancelRedeemRequest(uint256 requestId, address controller) external view returns (bool isPending);

    /**
     * @dev Returns the amount of shares that were canceled from a redeem Request, and can now be claimed.
     *
     * - MUST NOT show any variations depending on the caller.
     */
    function claimableCancelRedeemRequest(uint256 requestId, address controller)
        external
        view
        returns (uint256 claimableShares);

    /**
     * @dev Claims the canceled redeem shares, and removes the pending cancellation Request
     *
     * - controller MUST be msg.sender unless some unspecified explicit approval is given by the caller,
     *    approval of ERC-20 tokens from controller to sender is NOT enough.
     * - MUST set pendingCancelRedeemRequest to `false` for the returned requestId after request
     * - MUST set claimableCancelRedeemRequest to 0 for the returned requestId after fulfillment
     */
    function claimCancelRedeemRequest(uint256 requestId, address receiver, address controller)
        external
        returns (uint256 shares);
}

interface IERC7741 {
    /**
     * @dev Grants or revokes permissions for `operator` to manage Requests on behalf of the
     *      `msg.sender`, using an [EIP-712](./eip-712.md) signature.
     */
    function authorizeOperator(
        address controller,
        address operator,
        bool approved,
        bytes32 nonce,
        uint256 deadline,
        bytes memory signature
    ) external returns (bool);

    /**
     * @dev Revokes the given `nonce` for `msg.sender` as the `owner`.
     */
    function invalidateNonce(bytes32 nonce) external;

    /**
     * @dev Returns whether the given `nonce` has been used for the `controller`.
     */
    function authorizations(address controller, bytes32 nonce) external view returns (bool used);

    /**
     * @dev Returns the `DOMAIN_SEPARATOR` as defined according to EIP-712. The `DOMAIN_SEPARATOR
     *      should be unique to the contract and chain to prevent replay attacks from other domains,
     *      and satisfy the requirements of EIP-712, but is otherwise unconstrained.
     */
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

interface IERC7714 {
    /**
     * @dev Returns `true` if the `user` is permissioned to interact with the contract.
     */
    function isPermissioned(address controller) external view returns (bool);
}

src/misc/interfaces/IERC7575.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

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

interface IERC7575 is IERC165 {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
    event Withdraw(
        address indexed sender, address indexed receiver, address indexed owner, uint256 assets, uint256 shares
    );

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

    /**
     * @dev Returns the address of the share token
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function share() external view returns (address shareTokenAddress);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

interface IERC7575Share is IERC165 {
    event VaultUpdate(address indexed asset, address vault);

    /**
     * @dev Returns the address of the Vault for the given asset.
     *
     * @param asset the ERC-20 token to deposit with into the Vault
     */
    function vault(address asset) external view returns (address);
}

src/misc/interfaces/IERC7751.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// [ERC-7751](https://eips.ethereum.org/EIPS/eip-7751): Wrapping of bubbled up reverts
/// Handling bubbled up reverts using custom errors with additional context.
interface IERC7751 {
    error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
}

src/misc/interfaces/IMulticall.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @notice Allows to call several calls of the same contract in a single transaction
interface IMulticall {
    /// @notice Dispatched when an empty revert is dispatched in a method in the multicall
    error CallFailedWithEmptyRevert();

    /// @notice Allows caller to execute multiple (batched) messages calls in one transaction.
    /// @param data An array of encoded methods of the same contract.
    /// @dev No reentrant execution is allowed.
    ///         If one call fails, it reverts the whole transaction.
    ///         In order to provide the correct value for functions that require top up,
    ///         the caller must estimate separately, in advance, how much each of the message call will cost.
    ///         The `msg.value` when calling this method must be the sum of all estimates.
    function multicall(bytes[] calldata data) external payable;
}

src/misc/interfaces/IRecoverable.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

address constant ETH_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);

interface IRecoverable {
    /// @notice Used to recover any ERC-20 token.
    /// @dev    This method is called only by authorized entities
    /// @param  token It could be 0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
    ///         to recover locked native ETH or token compatible with ERC20.
    /// @param  to Receiver of the funds
    /// @param  amount Amount to send to the receiver.
    function recoverTokens(address token, address to, uint256 amount) external;

    /// @notice Used to recover any ERC-20 or ERC-6909 token.
    /// @dev    This method is called only by authorized entities
    /// @param  token It could be 0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
    ///         to recover locked native ETH or token compatible with ERC20 or ERC6909.
    /// @param  tokenId The token id, i.e. non-zero if the underlying token is ERC6909 and else zero.
    /// @param  to Receiver of the funds
    /// @param  amount Amount to send to the receiver.
    function recoverTokens(address token, uint256 tokenId, address to, uint256 amount) external;
}

src/misc/libraries/BytesLib.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

/// @title  Bytes Lib
/// @dev    Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
///         The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
/// @author Modified from Solidity Bytes Arrays Utils v0.8.0
library BytesLib {
    error SliceOverflow();
    error SliceOutOfBounds();

    function slice(bytes memory _bytes, uint256 _start, uint256 _length) internal pure returns (bytes memory) {
        unchecked {
            require(_length + 31 >= _length, SliceOverflow());
        }
        require(_bytes.length >= _start + _length, SliceOutOfBounds());

        bytes memory tempBytes;

        assembly {
            switch iszero(_length)
            case 0 {
                // Get a location of some free memory and store it in tempBytes as
                // Solidity does for memory variables.
                tempBytes := mload(0x40)

                // The first word of the slice result is potentially a partial
                // word read from the original array. To read it, we calculate
                // the length of that partial word and start copying that many
                // bytes into the array. The first word we copy will start with
                // data we don't care about, but the last `lengthmod` bytes will
                // land at the beginning of the contents of the new array. When
                // we're done copying, we overwrite the full first word with
                // the actual length of the slice.
                let lengthmod := and(_length, 31)

                // The multiplication in the next line is necessary
                // because when slicing multiples of 32 bytes (lengthmod == 0)
                // the following copy loop was copying the origin's length
                // and then ending prematurely not copying everything it should.
                let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
                let end := add(mc, _length)

                for {
                    // The multiplication in the next line has the same exact purpose
                    // as the one above.
                    let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
                } lt(mc, end) {
                    mc := add(mc, 0x20)
                    cc := add(cc, 0x20)
                } { mstore(mc, mload(cc)) }

                mstore(tempBytes, _length)

                //update free-memory pointer
                //allocating the array padded to 32 bytes like the compiler does now
                mstore(0x40, and(add(mc, 31), not(31)))
            }
            //if we want a zero-length slice let's just return a zero-length array
            default {
                tempBytes := mload(0x40)
                //zero out the 32 bytes slice we are about to return
                //we need to do it because Solidity does not garbage collect
                mstore(tempBytes, 0)

                mstore(0x40, add(tempBytes, 0x20))
            }
        }

        return tempBytes;
    }

    function sliceZeroPadded(bytes memory _bytes, uint256 _start, uint256 _length)
        internal
        pure
        returns (bytes memory)
    {
        bool needsPad = _bytes.length < _start + _length;
        if (!needsPad) return slice(_bytes, _start, _length);

        bytes memory slice_ = slice(_bytes, _start, _bytes.length - _start);
        bytes memory padding = new bytes(_length + _start - _bytes.length);
        return bytes.concat(slice_, padding);
    }

    function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
        require(_bytes.length >= _start + 20, SliceOutOfBounds());
        address tempAddress;

        assembly {
            tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
        }

        return tempAddress;
    }

    function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
        require(_bytes.length >= _start + 1, SliceOutOfBounds());
        uint8 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x1), _start))
        }

        return tempUint;
    }

    function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {
        require(_bytes.length >= _start + 2, SliceOutOfBounds());
        uint16 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x2), _start))
        }

        return tempUint;
    }

    function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {
        require(_bytes.length >= _start + 4, SliceOutOfBounds());
        uint32 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x4), _start))
        }

        return tempUint;
    }

    function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) {
        require(_bytes.length >= _start + 8, SliceOutOfBounds());
        uint64 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x8), _start))
        }

        return tempUint;
    }

    function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) {
        require(_bytes.length >= _start + 16, SliceOutOfBounds());
        uint128 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x10), _start))
        }

        return tempUint;
    }

    function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
        require(_bytes.length >= _start + 32, SliceOutOfBounds());
        uint256 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x20), _start))
        }

        return tempUint;
    }

    function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
        require(_bytes.length >= _start + 32, SliceOutOfBounds());
        bytes32 tempBytes32;

        assembly {
            tempBytes32 := mload(add(add(_bytes, 0x20), _start))
        }

        return tempBytes32;
    }

    function toBytes16(bytes memory _bytes, uint256 _start) internal pure returns (bytes16) {
        require(_bytes.length >= _start + 16, SliceOutOfBounds());
        bytes16 tempBytes16;

        assembly {
            tempBytes16 := mload(add(add(_bytes, 0x20), _start))
        }

        return tempBytes16;
    }

    function toBool(bytes memory _bytes, uint256 _start) internal pure returns (bool) {
        require(_bytes.length > _start, SliceOutOfBounds());
        return _bytes[_start] != 0;
    }

    function decodeCall(bytes calldata data) internal pure returns (bytes4 selector, bytes calldata payload) {
        require(data.length >= 4, SliceOutOfBounds());
        selector = bytes4(data[:4]);
        payload = data[4:];
    }
}

src/misc/libraries/CastLib.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

/// @title  CastLib
library CastLib {
    error PrefixNotZero();
    error SizeNot128();

    function toAddressLeftPadded(bytes32 addr) internal pure returns (address) {
        require(bytes12(addr) == 0, PrefixNotZero());
        return address(uint160(uint256(addr)));
    }

    function toBytes32LeftPadded(address addr) internal pure returns (bytes32) {
        return bytes32(uint256(uint160(addr)));
    }

    function toAddress(bytes32 addr) internal pure returns (address) {
        require(uint96(uint256(addr)) == 0, PrefixNotZero());
        return address(bytes20(addr));
    }

    function toBytes32(address addr) internal pure returns (bytes32) {
        return bytes32(bytes20(addr));
    }

    /// @dev Adds zero padding
    function toBytes32(string memory source) internal pure returns (bytes32) {
        return bytes32(bytes(source));
    }

    /// @dev Removes zero padding
    function bytes128ToString(bytes memory _bytes128) internal pure returns (string memory) {
        require(_bytes128.length == 128, SizeNot128());

        uint8 i = 0;
        while (i < 128 && _bytes128[i] != 0) {
            i++;
        }

        bytes memory bytesArray = new bytes(i);

        for (uint8 j; j < i; j++) {
            bytesArray[j] = _bytes128[j];
        }

        return string(bytesArray);
    }

    function toString(bytes32 _bytes32) internal pure returns (string memory) {
        uint8 i = 0;
        while (i < 32 && _bytes32[i] != 0) {
            i++;
        }
        bytes memory bytesArray = new bytes(i);
        for (i = 0; i < 32 && _bytes32[i] != 0; i++) {
            bytesArray[i] = _bytes32[i];
        }
        return string(bytesArray);
    }
}

src/misc/libraries/EIP712Lib.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

/// @title  EIP712 Lib
library EIP712Lib {
    // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
    bytes32 public constant EIP712_DOMAIN_TYPEHASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;

    function calculateDomainSeparator(bytes32 nameHash, bytes32 versionHash) internal view returns (bytes32) {
        return keccak256(abi.encode(EIP712_DOMAIN_TYPEHASH, nameHash, versionHash, block.chainid, address(this)));
    }
}

src/misc/libraries/MathLib.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

library MathLib {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    error MulDiv_Overflow();
    error Uint8_Overflow();
    error Uint16_Overflow();
    error Uint32_Overflow();
    error Uint64_Overflow();
    error Uint96_Overflow();
    error Uint128_Overflow();
    error Int128_Overflow();

    uint256 public constant One27 = 10 ** 27;

    /// @notice Returns x^n with rounding precision of base
    ///
    /// @dev Source: https://github.com/makerdao/dss/blob/fa4f6630afb0624d04a003e920b0d71a00331d98/src/jug.sol#L62
    ///
    /// @param x The base value which should be exponentiated
    /// @param n The exponent
    /// @param base The scaling base, typically used for fix-point calculations
    function rpow(uint256 x, uint256 n, uint256 base) public pure returns (uint256 z) {
        assembly {
            switch x
            case 0 {
                switch n
                case 0 { z := base }
                default { z := 0 }
            }
            default {
                switch mod(n, 2)
                case 0 { z := base }
                default { z := x }
                let half := div(base, 2) // for rounding.
                for { n := div(n, 2) } n { n := div(n, 2) } {
                    let xx := mul(x, x)
                    if iszero(eq(div(xx, x), x)) { revert(0, 0) }
                    let xxRound := add(xx, half)
                    if lt(xxRound, xx) { revert(0, 0) }
                    x := div(xxRound, base)
                    if mod(n, 2) {
                        let zx := mul(z, x)
                        if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0, 0) }
                        let zxRound := add(zx, half)
                        if lt(zxRound, zx) { revert(0, 0) }
                        z := div(zxRound, base)
                    }
                }
            }
        }
    }

    /// @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
    ///         denominator == 0
    /// @dev    Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
    ///         with further edits by Uniswap Labs also under MIT license.
    // slither-disable-start divide-before-multiply
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

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

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

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

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

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

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

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

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

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

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

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

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

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

    // slither-disable-end divide-before-multiply

    /// @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /// @notice Safe type conversion from uint256 to uint8.
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value <= type(uint8).max, Uint8_Overflow());
        return uint8(value);
    }

    /// @notice Safe type conversion from uint256 to uint16.
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value <= type(uint16).max, Uint16_Overflow());
        return uint16(value);
    }

    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value <= type(uint32).max, Uint32_Overflow());
        return uint32(value);
    }

    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value <= type(uint64).max, Uint64_Overflow());
        return uint64(value);
    }

    function toUint96(uint256 value) internal pure returns (uint96) {
        require(value <= type(uint96).max, Uint96_Overflow());
        return uint96(value);
    }

    /// @notice Safe type conversion from uint256 to uint128.
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value <= type(uint128).max, Uint128_Overflow());
        return uint128(value);
    }

    /// @notice Returns the smallest of two numbers.
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? b : a;
    }

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

    /// @notice Returns the absolute difference |a - b|, never underflows.
    function absDiff(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a - b : b - a;
    }
}

src/misc/libraries/SafeTransferLib.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

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

/// @title  Safe Transfer Lib
/// @author Modified from Uniswap v3 Periphery (libraries/TransferHelper.sol)
library SafeTransferLib {
    error NoCode();
    error SafeTransferFromFailed();
    error SafeTransferFailed();
    error SafeApproveFailed();
    error SafeTransferEthFailed();

    /// @notice Transfers tokens from the targeted address to the given destination
    /// @notice Errors if transfer fails
    /// @param token The contract address of the token to be transferred
    /// @param from The originating address from which the tokens will be transferred
    /// @param to The destination address of the transfer
    /// @param value The amount to be transferred
    function safeTransferFrom(address token, address from, address to, uint256 value) internal {
        require(address(token).code.length > 0, NoCode());

        (bool success, bytes memory returnData) = token.call(abi.encodeCall(IERC20.transferFrom, (from, to, value)));
        require(
            success && (returnData.length == 0 || abi.decode(returnData, (bool))),
            IERC7751.WrappedError(
                token, IERC20.transferFrom.selector, returnData, abi.encodeWithSelector(SafeTransferFromFailed.selector)
            )
        );
    }

    /// @notice Transfers tokens from msg.sender to a recipient
    /// @dev Errors if transfer fails
    /// @param token The contract address of the token which will be transferred
    /// @param to The recipient of the transfer
    /// @param value The value of the transfer
    function safeTransfer(address token, address to, uint256 value) internal {
        require(address(token).code.length > 0, NoCode());

        (bool success, bytes memory returnData) = token.call(abi.encodeCall(IERC20.transfer, (to, value)));
        require(
            success && (returnData.length == 0 || abi.decode(returnData, (bool))),
            IERC7751.WrappedError(
                token, IERC20.transfer.selector, returnData, abi.encodeWithSelector(SafeTransferFailed.selector)
            )
        );
    }

    /// @notice Approves the stipulated contract to spend the given allowance in the given token
    /// @dev Errors if approval fails
    /// @param token The contract address of the token to be approved
    /// @param to The target of the approval
    /// @param value The amount of the given token the target will be allowed to spend
    function safeApprove(address token, address to, uint256 value) internal {
        require(address(token).code.length > 0, NoCode());

        (bool success, bytes memory returnData) = token.call(abi.encodeCall(IERC20.approve, (to, value)));
        require(
            success && (returnData.length == 0 || abi.decode(returnData, (bool))),
            IERC7751.WrappedError(
                token, IERC20.approve.selector, returnData, abi.encodeWithSelector(SafeApproveFailed.selector)
            )
        );
    }

    /// @notice Transfers ETH to the recipient address
    /// @dev Reverts with `SafeTransferEthFailed` on failure
    /// @dev Make sure that method that is using this function is protected from reentrancy
    /// @param to The destination of the transfer
    /// @param value The value to be transferred
    function safeTransferETH(address to, uint256 value) internal {
        if (value == 0) return;
        (bool success,) = to.call{value: value}(new bytes(0));
        require(success, SafeTransferEthFailed());
    }
}

src/misc/libraries/SignatureLib.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

interface IERC1271 {
    function isValidSignature(bytes32, bytes memory) external view returns (bytes4);
}

/// @title  Signature Lib
library SignatureLib {
    error InvalidSigner();

    function isValidSignature(address signer, bytes32 digest, bytes memory signature)
        internal
        view
        returns (bool valid)
    {
        require(signer != address(0), InvalidSigner());

        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            if (signer == ecrecover(digest, v, r, s)) {
                return true;
            }
        }

        if (signer.code.length > 0) {
            (bool success, bytes memory result) =
                signer.staticcall(abi.encodeCall(IERC1271.isValidSignature, (digest, signature)));
            valid =
            (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector);
        }
    }
}

src/misc/types/D18.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.28;

// Small library to handle fixed point number operations with 18 decimals with static typing support.

import {MathLib} from "../libraries/MathLib.sol";

type D18 is uint128;

error D18_DivisionByZero();

using MathLib for uint256;

/// @dev add two D18 types
function add(D18 d1, D18 d2) pure returns (D18) {
    return D18.wrap(D18.unwrap(d1) + D18.unwrap(d2));
}

/// @dev subtract two D18 types
function sub(D18 d1, D18 d2) pure returns (D18) {
    return D18.wrap(D18.unwrap(d1) - D18.unwrap(d2));
}

/// @dev Divides one D18 by another one while retaining precision:
/// - nominator (decimal): 50e18
/// - denominator (decimal):  2e19
/// - result (decimal): 25e17
function divD18(D18 d1, D18 d2) pure returns (D18) {
    return D18.wrap(MathLib.mulDiv(D18.unwrap(d1), 1e18, D18.unwrap(d2)).toUint128());
}

/// @dev Multiplies one D18 with another one while retaining precision:
/// - value1 (decimal): 50e18
/// - value2 (decimal):  2e19
/// - result (decimal): 100e19
function mulD18(D18 d1, D18 d2) pure returns (D18) {
    return D18.wrap(MathLib.mulDiv(D18.unwrap(d1), D18.unwrap(d2), 1e18).toUint128());
}

/// @dev Returns the reciprocal of a D18 decimal, i.e. 1 / d.
///      Example: if d = 2.0 (2e18 internally), reciprocal(d) = 0.5 (5e17 internally).
function reciprocal(D18 d) pure returns (D18) {
    uint128 val = D18.unwrap(d);
    require(val != 0, D18_DivisionByZero());
    return d18(1e18, val);
}

/// @dev Multiplies a decimal by an integer. i.e:
/// - d (decimal):      1_500_000_000_000_000_000
/// - value (integer):  4_000_000_000_000_000_000
/// - result (integer): 6_000_000_000_000_000_000
function mulUint128(D18 d, uint128 value, MathLib.Rounding rounding) pure returns (uint128) {
    return MathLib.mulDiv(D18.unwrap(d), value, 1e18, rounding).toUint128();
}

/// @dev Multiplies a decimal by an integer. i.e:
/// - d (decimal):      1_500_000_000_000_000_000
/// - value (integer):  4_000_000_000_000_000_000
/// - result (integer): 6_000_000_000_000_000_000
function mulUint256(D18 d, uint256 value, MathLib.Rounding rounding) pure returns (uint256) {
    return MathLib.mulDiv(D18.unwrap(d), value, 1e18, rounding);
}

/// @dev  Divides an integer by a decimal, i.e.:
/// - d (decimal):      2_000_000_000_000_000_000
/// - value (integer):  100_000_000_000_000_000_000
/// - result (integer): 50_000_000_000_000_000_000
function reciprocalMulUint128(D18 d, uint128 value, MathLib.Rounding rounding) pure returns (uint128) {
    return MathLib.mulDiv(value, 1e18, d.raw(), rounding).toUint128();
}

/// @dev  Divides an integer by a decimal, i.e.:
/// - d (decimal):      2_000_000_000_000_000_000
/// - value (integer):  100_000_000_000_000_000_000
/// - result (integer): 50_000_000_000_000_000_000
function reciprocalMulUint256(D18 d, uint256 value, MathLib.Rounding rounding) pure returns (uint256) {
    return MathLib.mulDiv(value, 1e18, d.raw(), rounding);
}

/// @dev Easy way to construct a decimal number
function d18(uint128 value) pure returns (D18) {
    return D18.wrap(value);
}

/// @dev Easy way to construct a decimal number
function d18(uint128 num, uint128 den) pure returns (D18) {
    return D18.wrap(MathLib.mulDiv(num, 1e18, den).toUint128());
}

function eq(D18 a, D18 b) pure returns (bool) {
    return D18.unwrap(a) == D18.unwrap(b);
}

function isZero(D18 a) pure returns (bool) {
    return D18.unwrap(a) == 0;
}

function isNotZero(D18 a) pure returns (bool) {
    return D18.unwrap(a) != 0;
}

function raw(D18 d) pure returns (uint128) {
    return D18.unwrap(d);
}

/// @dev True iff `value` is within `maxDeviation` of the reference value.
///      Boundary is inclusive. NOTE: Strict equality via maxDeviation == 0.
function withinDeviation(D18 value, D18 reference_, uint128 maxDeviation) pure returns (bool) {
    uint256 ref = reference_.raw();
    uint256 delta = MathLib.absDiff(value.raw(), ref);
    // Cross-multiply to avoid ceil-rounding: rewrite delta/ref <= maxDeviation/1e18 without division.
    return delta * 1e18 <= uint256(maxDeviation) * ref;
}

using {
    add as +,
    sub as -,
    divD18 as /,
    eq as ==,
    mulD18 as *,
    mulUint128,
    mulUint256,
    reciprocalMulUint128,
    reciprocalMulUint256,
    reciprocal,
    raw,
    isZero,
    isNotZero,
    withinDeviation
} for D18 global;

src/token/interfaces/IShareToken.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {IERC1404} from "../../misc/interfaces/IERC1404.sol";
import {IERC20Metadata} from "../../misc/interfaces/IERC20.sol";
import {IERC7575Share} from "../../misc/interfaces/IERC7575.sol";

interface IShareToken is IERC20Metadata, IERC7575Share, IERC1404 {
    //----------------------------------------------------------------------------------------------
    // Events
    //----------------------------------------------------------------------------------------------

    event File(bytes32 indexed what, address data);
    event SetHookData(address indexed user, bytes16 data);

    //----------------------------------------------------------------------------------------------
    // Errors
    //----------------------------------------------------------------------------------------------

    error NotAuthorizedOrHook();
    error ExceedsMaxSupply();
    error RestrictionsFailed();

    //----------------------------------------------------------------------------------------------
    // Structs
    //----------------------------------------------------------------------------------------------

    struct Balance {
        /// @dev The user balance is limited to uint128. This is safe because the decimals are limited to 18,
        ///      thus the max balance is 2^128-1 / 10**18 = 3.40 * 10**20. This is also enforced on mint.
        uint128 amount;
        /// @dev There are 16 bytes that are used to store hook data (e.g. restrictions for users).
        bytes16 hookData;
    }

    //----------------------------------------------------------------------------------------------
    // Administration
    //----------------------------------------------------------------------------------------------

    /// @notice Returns the hook that transfers perform callbacks to
    /// @dev MUST comply to `ITransferHook` interface
    /// @return The hook contract address
    function hook() external view returns (address);

    /// @notice Updates a contract parameter
    /// @param what Accepts a bytes32 representation of 'name', 'symbol'
    /// @param data The new string value
    function file(bytes32 what, string memory data) external;

    /// @notice Updates a contract parameter
    /// @param what Accepts a bytes32 representation of 'hook'
    /// @param data The new address value
    function file(bytes32 what, address data) external;

    /// @notice Updates the vault for a given `asset`
    /// @param asset The asset address
    /// @param vault_ The vault address
    function updateVault(address asset, address vault_) external;

    //----------------------------------------------------------------------------------------------
    // ERC20 overrides
    //----------------------------------------------------------------------------------------------

    /// @notice Returns the 16 byte hook data of the given `user`
    /// @dev Stored in the 128 most significant bits of the user balance
    /// @param user The user address
    /// @return The 16 byte hook data
    function hookDataOf(address user) external view returns (bytes16);

    /// @notice Update the 16 byte hook data of the given `user`
    /// @param user The user address
    /// @param hookData The new hook data
    function setHookData(address user, bytes16 hookData) external;

    /// @notice Function to mint tokens
    /// @param user The address to mint tokens to
    /// @param value The amount of tokens to mint
    function mint(address user, uint256 value) external;

    /// @notice Function to burn tokens
    /// @param user The address to burn tokens from
    /// @param value The amount of tokens to burn
    function burn(address user, uint256 value) external;

    /// @notice Checks if the tokens can be transferred given the input values
    /// @param from The sender address
    /// @param to The recipient address
    /// @param value The amount to transfer
    /// @return Whether the transfer is allowed
    function checkTransferRestriction(address from, address to, uint256 value) external view returns (bool);

    /// @notice Performs an authorized transfer, with `sender` as the given sender
    /// @dev Requires allowance if `sender` != `from`
    /// @param sender The address initiating the transfer
    /// @param from The address to transfer from
    /// @param to The address to transfer to
    /// @param amount The amount to transfer
    /// @return Whether the transfer succeeded
    function authTransferFrom(address sender, address from, address to, uint256 amount) external returns (bool);
}

src/utils/interfaces/IRefundEscrow.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @notice Simple escrow that can be used to deposit and withdraw native tokens
interface IRefundEscrow {
    /// @notice Dispatched when the given funds can not be withdrawed
    error CannotWithdraw();

    /// @notice Deposit `msg.value` funds to this contract
    function depositFunds() external payable;

    /// @notice Withdraw `value` funds to `to` address
    /// @param to The address to send the withdrawn funds to
    /// @param value The amount of native tokens to withdraw
    function withdrawFunds(address to, uint256 value) external;
}

src/utils/interfaces/IRefundEscrowFactory.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

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

import {PoolId} from "../../core/types/PoolId.sol";

/// @title  IRefundEscrowFactory
/// @notice Factory for deploying refund escrow contracts for vault operations
/// @dev    Each pool has a unique refund escrow for handling failed deposits
interface IRefundEscrowFactory {
    event File(bytes32 what, address data);
    event DeployRefundEscrow(PoolId indexed poolId, address indexed escrow);

    error FileUnrecognizedParam();

    /// @notice SubsidyManager authorized to deploy escrows and withdraw subsidy funds
    function controller() external view returns (address);

    /// @notice Root authority that manages ward permissions and timelocked upgrades
    function root() external view returns (address);

    /// @notice Updates contract parameters of type address.
    /// @param what The parameter name to update
    /// @param data The new address value
    function file(bytes32 what, address data) external;

    /// @notice Deploys new escrow and returns it.
    /// @param poolId The pool identifier for which to deploy the escrow
    /// @return The newly deployed refund escrow contract
    function newEscrow(PoolId poolId) external returns (IRefundEscrow);

    /// @notice Returns the escrow
    /// @param poolId The pool identifier
    /// @return The refund escrow contract for the pool
    function get(PoolId poolId) external view returns (IRefundEscrow);
}

src/utils/interfaces/ISubsidyManager.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

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

import {PoolId} from "../../core/types/PoolId.sol";
import {IManagerCallFromHub} from "../../core/utils/interfaces/IManagerCall.sol";

interface ISubsidyManager is IManagerCallFromHub {
    event File(bytes32 indexed what, address data);
    event DepositSubsidy(PoolId indexed poolId, address indexed sender, uint256 amount);
    event WithdrawSubsidy(PoolId indexed poolId, address indexed sender, uint256 amount);

    error FileUnrecognizedParam();
    error RefundEscrowNotDeployed();
    error NotEnoughToWithdraw();
    error NotEnvoy();
    error UnexpectedValue();

    /// @notice The Envoy that routes policy-supervised subsidy withdrawals
    function envoy() external view returns (address);

    /// @notice Factory that deploys per-pool refund escrows for holding subsidy deposits
    function refundEscrowFactory() external view returns (IRefundEscrowFactory);

    /// @notice Updates contract parameters of type address.
    /// @param what The bytes32 representation of 'refundEscrowFactory' or 'envoy'.
    /// @param data The new contract address.
    function file(bytes32 what, address data) external;

    /// @notice Deposit funds to subsidy vault actions through the gateway
    function deposit(PoolId poolId) external payable;

    /// @notice Withdraw subsidized funds to an account
    function withdraw(PoolId poolId, address to, uint256 value) external;

    /// @notice Withdraws all subsidized funds to an account for cross-chain message payment.
    /// @dev Unlike `withdraw()`, this function does not emit a `WithdrawSubsidy` event because
    ///      it is used as a utility to temporarily withdraw funds for
    ///      paying cross-chain messages. The excess funds are refunded back to the RefundEscrow
    ///      in the same transaction (or asynchronously shortly after), so no actual withdrawal
    ///      from the subsidy system occurs.
    /// @param poolId The pool whose subsidy escrow to withdraw from.
    /// @param to The address to send the funds to (typically the caller for message payment).
    /// @return The escrow address from where the subsidy is withdrawn.
    /// @return amount The amount withdrawn.
    function withdrawAll(PoolId poolId, address to) external returns (address, uint256 amount);
}

src/vaults/BaseVaults.sol

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

import {IBaseVault} from "./interfaces/IBaseVault.sol";
import {IAsyncRedeemVault} from "./interfaces/IAsyncVault.sol";
import {IBaseRequestManager} from "./interfaces/IBaseRequestManager.sol";
import {IAsyncRedeemManager, ISyncDepositManager} from "./interfaces/IVaultManagers.sol";

import {Auth} from "../misc/Auth.sol";
import {Recoverable} from "../misc/Recoverable.sol";
import {EIP712Lib} from "../misc/libraries/EIP712Lib.sol";
import {IERC20Metadata} from "../misc/interfaces/IERC20.sol";
import {SignatureLib} from "../misc/libraries/SignatureLib.sol";
import {IERC165, IERC7575} from "../misc/interfaces/IERC7575.sol";
import {SafeTransferLib} from "../misc/libraries/SafeTransferLib.sol";
import {IERC7540Operator, IERC7540Redeem, IERC7714, IERC7741, IERC7887Redeem} from "../misc/interfaces/IERC7540.sol";

import {PoolId} from "../core/types/PoolId.sol";
import {ShareClassId} from "../core/types/ShareClassId.sol";

import {IRoot} from "../admin/interfaces/IRoot.sol";

import {IShareToken} from "../token/interfaces/IShareToken.sol";

abstract contract BaseVault is Auth, Recoverable, IBaseVault {
    /// @dev Requests for Centrifuge pool are non-fungible and all have ID = 0
    uint256 internal constant REQUEST_ID = 0;

    IRoot public immutable root;
    IBaseRequestManager public baseManager;

    /// @inheritdoc IBaseVault
    PoolId public immutable poolId;
    /// @inheritdoc IBaseVault
    ShareClassId public immutable scId;

    /// @inheritdoc IERC7575
    address public immutable asset;

    /// @inheritdoc IERC7575
    address public immutable share;
    uint8 internal immutable _shareDecimals;

    /// --- ERC7741 ---
    bytes32 private immutable nameHash;
    bytes32 private immutable versionHash;
    uint256 public immutable deploymentChainId;
    bytes32 private immutable _DOMAIN_SEPARATOR;
    bytes32 public constant AUTHORIZE_OPERATOR_TYPEHASH = keccak256(
        "AuthorizeOperator(address controller,address operator,bool approved,bytes32 nonce,uint256 deadline)"
    );

    /// @inheritdoc IERC7741
    mapping(address controller => mapping(bytes32 nonce => bool used)) public authorizations;

    /// @inheritdoc IERC7540Operator
    /// @dev Approval covers the controller's whole position, not this vault's share of it: an operator can
    ///      move the controller's free balance into a request and claim the proceeds to any receiver. The hub
    ///      keys requests by (pool, share class, asset) and investor, so vaults linked to one such tuple share
    ///      a single position. A settlement for that position is applied to the vault named by the share
    ///      token's pointer, and an operator approved on that vault reaches the investor's whole tuple
    ///      position, including requests made through the other linked vaults. An operator approved only
    ///      elsewhere reaches nothing unless the pool re-points.
    mapping(address => mapping(address => bool)) public isOperator;

    constructor(
        PoolId poolId_,
        ShareClassId scId_,
        address asset_,
        IShareToken token_,
        address root_,
        IBaseRequestManager manager_
    ) Auth(msg.sender) {
        poolId = poolId_;
        scId = scId_;
        asset = asset_;
        share = address(token_);
        _shareDecimals = IERC20Metadata(share).decimals();
        root = IRoot(root_);
        baseManager = IBaseRequestManager(manager_);

        nameHash = keccak256(bytes("Centrifuge"));
        versionHash = keccak256(bytes("1"));
        deploymentChainId = block.chainid;
        _DOMAIN_SEPARATOR = EIP712Lib.calculateDomainSeparator(nameHash, versionHash);
    }

    //----------------------------------------------------------------------------------------------
    // Administration
    //----------------------------------------------------------------------------------------------

    function file(bytes32 what, address data) external virtual auth {
        if (what == "manager") baseManager = IBaseRequestManager(data);
        else revert FileUnrecognizedParam();
        emit File(what, data);
    }

    /// @inheritdoc IERC7540Operator
    function setOperator(address operator, bool approved) public virtual returns (bool success) {
        require(msg.sender != operator, CannotSetSelfAsOperator());
        isOperator[msg.sender][operator] = approved;
        emit OperatorSet(msg.sender, operator, approved);
        success = true;
    }

    /// @inheritdoc IBaseVault
    function setEndorsedOperator(address owner, bool approved) public virtual {
        require(msg.sender != owner, CannotSetSelfAsOperator());
        require(root.endorsed(msg.sender), NotEndorsed());
        isOperator[owner][msg.sender] = approved;
        emit OperatorSet(owner, msg.sender, approved);
    }

    /// @inheritdoc IERC7741
    function DOMAIN_SEPARATOR() public view returns (bytes32) {
        return block.chainid == deploymentChainId
            ? _DOMAIN_SEPARATOR
            : EIP712Lib.calculateDomainSeparator(nameHash, versionHash);
    }

    /// @inheritdoc IERC7741
    function authorizeOperator(
        address controller,
        address operator,
        bool approved,
        bytes32 nonce,
        uint256 deadline,
        bytes memory signature
    ) external returns (bool success) {
        require(controller != operator, CannotSetSelfAsOperator());
        require(block.timestamp <= deadline, ExpiredAuthorization());
        require(!authorizations[controller][nonce], AlreadyUsedAuthorization());

        authorizations[controller][nonce] = true;

        bytes32 digest = keccak256(
            abi.encodePacked(
                "\x19\x01",
                DOMAIN_SEPARATOR(),
                keccak256(abi.encode(AUTHORIZE_OPERATOR_TYPEHASH, controller, operator, approved, nonce, deadline))
            )
        );

        require(SignatureLib.isValidSignature(controller, digest, signature), InvalidAuthorization());

        isOperator[controller][operator] = approved;
        emit OperatorSet(controller, operator, approved);

        success = true;
    }

    /// @inheritdoc IERC7741
    function invalidateNonce(bytes32 nonce) external {
        authorizations[msg.sender][nonce] = true;
    }

    //----------------------------------------------------------------------------------------------
    // ERC-165
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public pure virtual override returns (bool) {
        return interfaceId == type(IERC7540Operator).interfaceId || interfaceId == type(IERC7741).interfaceId
            || interfaceId == type(IERC7714).interfaceId || interfaceId == type(IERC7575).interfaceId
            || interfaceId == type(IERC165).interfaceId;
    }

    //----------------------------------------------------------------------------------------------
    // ERC-4626
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IERC7575
    function totalAssets() external view returns (uint256) {
        return convertToAssets(IERC20Metadata(share).totalSupply());
    }

    /// @inheritdoc IERC7575
    /// @notice     The calculation is based on the token price from the most recent epoch retrieved from Centrifuge.
    ///             The actual conversion MAY change between order submission and execution.
    function convertToShares(uint256 assets) public view returns (uint256 shares) {
        shares = baseManager.convertToShares(this, assets);
    }

    /// @inheritdoc IERC7575
    /// @notice     The calculation is based on the token price from the most recent epoch retrieved from Centrifuge.
    ///             The actual conversion MAY change between order submission and execution.
    function convertToAssets(uint256 shares) public view returns (uint256 assets) {
        assets = baseManager.convertToAssets(this, shares);
    }

    //----------------------------------------------------------------------------------------------
    // Helpers
    //----------------------------------------------------------------------------------------------

    /// @notice Price of 1 unit of share, quoted in the decimals of the asset.
    function pricePerShare() external view returns (uint256) {
        return convertToAssets(10 ** _shareDecimals);
    }

    /// @notice Returns timestamp of the last share price update.
    function priceLastUpdated() external view returns (uint64) {
        return baseManager.priceLastUpdated(this);
    }

    /// @inheritdoc IERC7714
    function isPermissioned(address controller) external view returns (bool) {
        return IShareToken(share).checkTransferRestriction(address(0), controller, 0);
    }

    /// @notice Ensures msg.sender can operate on behalf of controller.
    function _validateController(address controller) internal view {
        require(controller == msg.sender || isOperator[controller][msg.sender], InvalidController());
    }
}

abstract contract BaseAsyncRedeemVault is BaseVault, IAsyncRedeemVault {
    IAsyncRedeemManager public asyncRedeemManager;

    constructor(IAsyncRedeemManager asyncRequestManager_) {
        asyncRedeemManager = asyncRequestManager_;
    }

    //----------------------------------------------------------------------------------------------
    // Administration
    //----------------------------------------------------------------------------------------------

    function file(bytes32 what, address data) external virtual override auth {
        if (what == "manager") baseManager = IBaseRequestManager(data);
        else if (what == "asyncRedeemManager") asyncRedeemManager = IAsyncRedeemManager(data);
        else revert FileUnrecognizedParam();
        emit File(what, data);
    }

    //----------------------------------------------------------------------------------------------
    // ERC-7540 redeem
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IERC7540Redeem
    function requestRedeem(uint256 shares, address controller, address owner) public returns (uint256) {
        require(IShareToken(share).balanceOf(owner) >= shares, InsufficientBalance());

        // If msg.sender is operator of owner, the transfer is executed as if
        // the sender is the owner, to bypass the allowance check
        address sender = isOperator[owner][msg.sender] ? owner : msg.sender;

        require(asyncRedeemManager.requestRedeem(this, shares, controller, owner, sender, true), RequestRedeemFailed());

        emit RedeemRequest(controller, owner, REQUEST_ID, msg.sender, shares);
        return REQUEST_ID;
    }

    /// @inheritdoc IERC7540Redeem
    function pendingRedeemRequest(uint256, address controller) public view returns (uint256 pendingShares) {
        pendingShares = asyncRedeemManager.pendingRedeemRequest(this, controller);
    }

    /// @inheritdoc IERC7540Redeem
    function claimableRedeemRequest(uint256, address controller) external view returns (uint256 claimableShares) {
        claimableShares = maxRedeem(controller);
    }

    //----------------------------------------------------------------------------------------------
    // ERC-7887
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IERC7887Redeem
    function cancelRedeemRequest(uint256, address controller) external {
        _validateController(controller);
        asyncRedeemManager.cancelRedeemRequest(this, controller, msg.sender);
        emit CancelRedeemRequest(controller, REQUEST_ID, msg.sender);
    }

    /// @inheritdoc IERC7887Redeem
    function pendingCancelRedeemRequest(uint256, address controller) public view returns (bool isPending) {
        isPending = asyncRedeemManager.pendingCancelRedeemRequest(this, controller);
    }

    /// @inheritdoc IERC7887Redeem
    function claimableCancelRedeemRequest(uint256, address controller) public view returns (uint256 claimableShares) {
        claimableShares = asyncRedeemManager.claimableCancelRedeemRequest(this, controller);
    }

    /// @inheritdoc IERC7887Redeem
    function claimCancelRedeemRequest(uint256, address receiver, address controller) external returns (uint256 shares) {
        _validateController(controller);
        shares = asyncRedeemManager.claimCancelRedeemRequest(this, receiver, controller);
        emit CancelRedeemClaim(controller, receiver, REQUEST_ID, msg.sender, shares);
    }

    //----------------------------------------------------------------------------------------------
    // ERC-7540 claim
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IERC7575
    /// @notice     DOES NOT support controller != msg.sender since shares are already transferred on requestRedeem
    function withdraw(uint256 assets, address receiver, address controller) public returns (uint256 shares) {
        _validateController(controller);
        shares = asyncRedeemManager.withdraw(this, assets, receiver, controller);
        emit Withdraw(msg.sender, receiver, controller, assets, shares);
    }

    /// @inheritdoc IERC7575
    /// @notice     DOES NOT support controller != msg.sender since shares are already transferred on requestRedeem.
    ///             When claiming redemption requests using redeem(), there can be some precision loss leading to dust.
    ///             It is recommended to use withdraw() to claim redemption requests instead.
    function redeem(uint256 shares, address receiver, address controller) external returns (uint256 assets) {
        _validateController(controller);
        assets = asyncRedeemManager.redeem(this, shares, receiver, controller);
        emit Withdraw(msg.sender, receiver, controller, assets, shares);
    }

    //----------------------------------------------------------------------------------------------
    // Event emitters
    //----------------------------------------------------------------------------------------------

    function onRedeemRequest(address controller, address owner, uint256 shares) public virtual auth {
        emit RedeemRequest(controller, owner, REQUEST_ID, msg.sender, shares);
    }

    function onRedeemClaimable(address controller, uint256 assets, uint256 shares) public virtual auth {
        emit RedeemClaimable(controller, REQUEST_ID, assets, shares);
    }

    function onCancelRedeemClaimable(address controller, uint256 shares) public virtual auth {
        emit CancelRedeemClaimable(controller, REQUEST_ID, shares);
    }

    //----------------------------------------------------------------------------------------------
    // View methods
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public pure virtual override(BaseVault, IERC165) returns (bool) {
        return super.supportsInterface(interfaceId) || interfaceId == type(IERC7540Redeem).interfaceId
            || interfaceId == type(IERC7887Redeem).interfaceId;
    }

    /// @inheritdoc IERC7575
    function maxWithdraw(address controller) public view returns (uint256 maxAssets) {
        maxAssets = asyncRedeemManager.maxWithdraw(this, controller);
    }

    /// @inheritdoc IERC7575
    function maxRedeem(address controller) public view returns (uint256 maxShares) {
        maxShares = asyncRedeemManager.maxRedeem(this, controller);
    }

    /// @dev Preview functions for ERC-7540 vaults revert
    function previewWithdraw(uint256) external pure returns (uint256) {
        revert();
    }

    /// @dev Preview functions for ERC-7540 vaults revert
    function previewRedeem(uint256) external pure returns (uint256) {
        revert();
    }
}

abstract contract BaseSyncDepositVault is BaseVault {
    ISyncDepositManager public syncDepositManager;

    constructor(ISyncDepositManager syncManager_) {
        syncDepositManager = syncManager_;
    }

    //----------------------------------------------------------------------------------------------
    // ERC-4626
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IERC7575
    function maxDeposit(address owner) public view returns (uint256 maxAssets) {
        maxAssets = syncDepositManager.maxDeposit(this, owner);
    }

    /// @inheritdoc IERC7575
    function previewDeposit(uint256 assets) external view override returns (uint256 shares) {
        shares = syncDepositManager.previewDeposit(this, msg.sender, assets);
    }

    /// @inheritdoc IERC7575
    function deposit(uint256 assets, address receiver) external returns (uint256 shares) {
        shares = syncDepositManager.deposit(this, assets, receiver, msg.sender);
        // NOTE: For security reasons, transfer must stay at end of call despite the fact that it logically should
        // happen before depositing in the manager
        SafeTransferLib.safeTransferFrom(asset, msg.sender, address(baseManager.poolEscrow(poolId)), assets);
        emit Deposit(msg.sender, receiver, assets, shares);
    }

    /// @inheritdoc IERC7575
    function maxMint(address owner) public view returns (uint256 maxShares) {
        maxShares = syncDepositManager.maxMint(this, owner);
    }

    /// @inheritdoc IERC7575
    function previewMint(uint256 shares) external view returns (uint256 assets) {
        assets = syncDepositManager.previewMint(this, msg.sender, shares);
    }

    /// @inheritdoc IERC7575
    function mint(uint256 shares, address receiver) public returns (uint256 assets) {
        assets = syncDepositManager.mint(this, shares, receiver, msg.sender);
        // NOTE: For security reasons, transfer must stay at end of call
        SafeTransferLib.safeTransferFrom(asset, msg.sender, address(baseManager.poolEscrow(poolId)), assets);
        emit Deposit(msg.sender, receiver, assets, shares);
    }

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public pure virtual override(BaseVault) returns (bool) {
        return super.supportsInterface(interfaceId);
    }
}

src/vaults/interfaces/IAsyncVault.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {IBaseVault} from "./IBaseVault.sol";
import {IAsyncRedeemManager, IAsyncRequestManager} from "./IVaultManagers.sol";

import {IERC7540Redeem, IERC7887Redeem, IERC7887Deposit, IERC7540Deposit} from "../../misc/interfaces/IERC7540.sol";

/**
 * @title  IAsyncRedeemVault
 * @dev    This is the specific set of interfaces used by the Centrifuge implementation of ERC7540,
 *         as a fully asynchronous Vault, with cancellation support, and authorize operator signature support.
 */
interface IAsyncRedeemVault is IERC7540Redeem, IERC7887Redeem, IBaseVault {
    event RedeemClaimable(address indexed controller, uint256 indexed requestId, uint256 assets, uint256 shares);
    event CancelRedeemClaimable(address indexed controller, uint256 indexed requestId, uint256 shares);

    /// @notice Callback invoked when a redeem request is triggered externally
    /// @param controller The address controlling the request
    /// @param owner The address that owns the shares
    /// @param shares The amount of shares to redeem
    function onRedeemRequest(address controller, address owner, uint256 shares) external;

    /// @notice Callback invoked when a redeem request becomes claimable
    /// @param owner The address that can claim the assets
    /// @param assets The amount of assets available to claim
    /// @param shares The amount of shares that were redeemed
    function onRedeemClaimable(address owner, uint256 assets, uint256 shares) external;

    /// @notice Callback invoked when a cancelled redeem request becomes claimable
    /// @param owner The address that can claim the returned shares
    /// @param shares The amount of shares being returned
    function onCancelRedeemClaimable(address owner, uint256 shares) external;

    /// @notice Get the asynchronous redeem manager for this vault
    /// @return The async redeem manager contract
    function asyncRedeemManager() external view returns (IAsyncRedeemManager);
}

interface IAsyncVault is IERC7540Deposit, IERC7887Deposit, IAsyncRedeemVault {
    event DepositClaimable(address indexed controller, uint256 indexed requestId, uint256 assets, uint256 shares);
    event CancelDepositClaimable(address indexed controller, uint256 indexed requestId, uint256 assets);

    error InvalidOwner();
    error RequestDepositFailed();

    /// @notice Callback invoked when a deposit request becomes claimable
    /// @param owner The address that can claim the shares
    /// @param assets The amount of assets that were deposited
    /// @param shares The amount of shares available to claim
    function onDepositClaimable(address owner, uint256 assets, uint256 shares) external;

    /// @notice Callback invoked when a cancelled deposit request becomes claimable
    /// @param owner The address that can claim the returned assets
    /// @param assets The amount of assets being returned
    function onCancelDepositClaimable(address owner, uint256 assets) external;

    /// @notice Strongly-typed accessor to the generic async redeem manager as IAsyncRequestManager
    function asyncManager() external view returns (IAsyncRequestManager);
}

src/vaults/interfaces/IBaseRequestManager.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

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

import {PoolId} from "../../core/types/PoolId.sol";
import {ISpoke} from "../../core/spoke/interfaces/ISpoke.sol";
import {IEscrow} from "../../core/spoke/interfaces/IEscrow.sol";
import {ISpokeRequestManager} from "../../core/spoke/interfaces/ISpokeRequestManager.sol";

interface IBaseRequestManager is ISpokeRequestManager {
    event File(bytes32 indexed what, address data);

    error FileUnrecognizedParam();

    /// @notice Updates contract parameters of type address.
    /// @param what The bytes32 representation of 'spoke', etc.
    /// @param data The new contract address.
    function file(bytes32 what, address data) external;

    /// @notice Converts the assets value to share decimals.
    function convertToShares(IBaseVault vault, uint256 _assets) external view returns (uint256 shares);

    /// @notice Converts the shares value to assets decimals.
    function convertToAssets(IBaseVault vault, uint256 _shares) external view returns (uint256 assets);

    /// @notice Returns the timestamp of the last share price update for a vaultAddr.
    function priceLastUpdated(IBaseVault vault) external view returns (uint64 lastUpdated);

    /// @notice Returns the Spoke contract address.
    function spoke() external view returns (ISpoke spoke);

    /// @notice DEPRECATED: Returns the pool escrow for the calling vault's pool.
    /// NOTE: DEPRECATED IMPLEMENTATION: This function is maintained solely for ABI backward compatibility
    ///      with deployed vaults that call this function.
    ///      Despite the misleading "globalEscrow" name, this implementation returns the pool-specific
    ///      but NOT a global escrow. The global escrow concept was deprecated in v3.1.
    function globalEscrow() external view returns (IEscrow escrow);

    /// @notice Escrow per pool. Funds are associated to a specific pool
    /// @dev Kept under this name for ABI backward compatibility with deployed vaults, like `globalEscrow` above,
    ///      even though the contract it returns is now `Escrow` rather than `PoolEscrow`.
    function poolEscrow(PoolId poolId) external view returns (IEscrow);
}

src/vaults/interfaces/IBaseVault.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

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

import {IERC7575} from "../../misc/interfaces/IERC7575.sol";
import {IRecoverable} from "../../misc/interfaces/IRecoverable.sol";
import {IERC7540Operator, IERC7714, IERC7741} from "../../misc/interfaces/IERC7540.sol";

import {PoolId} from "../../core/types/PoolId.sol";
import {ShareClassId} from "../../core/types/ShareClassId.sol";

import {IRoot} from "../../admin/interfaces/IRoot.sol";

/// @notice Interface for the all vault contracts
/// @dev Must be implemented by all vaults
interface IBaseVault is IERC7540Operator, IERC7741, IERC7714, IERC7575, IRecoverable {
    error FileUnrecognizedParam();
    error NotEndorsed();
    error CannotSetSelfAsOperator();
    error ExpiredAuthorization();
    error AlreadyUsedAuthorization();
    error InvalidAuthorization();
    error InvalidController();
    error InsufficientBalance();
    error RequestRedeemFailed();
    error TransferFromFailed();

    event File(bytes32 indexed what, address data);

    /// @notice Set msg.sender as operator of owner, to `approved` status
    /// @dev    MUST be called by endorsed sender
    function setEndorsedOperator(address owner, bool approved) external;

    /// @notice Identifier of the Centrifuge pool
    /// @dev    Mirrors the vault's construction parameter, kept for integrator convenience. The registry
    ///         (`SpokeRegistry.vaultDetails`) is the authority on which pool a vault belongs to.
    /// @return The pool identifier
    function poolId() external view returns (PoolId);

    /// @notice Identifier of the share class of the Centrifuge pool
    /// @dev    See {poolId} on where the association is authoritative
    /// @return The share class identifier
    function scId() external view returns (ShareClassId);

    /// @notice Root authority that manages ward permissions and timelocked upgrades
    function root() external view returns (IRoot);

    /// @notice Request manager handling common deposit/redeem state (shared across vault types)
    function baseManager() external view returns (IBaseRequestManager);

    /// @notice EVM chain ID captured at construction, used for EIP-712 domain separator replay protection
    function deploymentChainId() external view returns (uint256);

    /// @notice keccak256 hash of the EIP-712 structured data type, needed for off-chain signature construction
    function AUTHORIZE_OPERATOR_TYPEHASH() external view returns (bytes32);

    /// @notice Price of 1 unit of share, quoted in the decimals of the asset
    function pricePerShare() external view returns (uint256);

    /// @notice Returns timestamp of the last share price update
    function priceLastUpdated() external view returns (uint64);
}

src/vaults/interfaces/IVaultManagers.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {IBaseVault} from "./IBaseVault.sol";
import {IBaseRequestManager} from "./IBaseRequestManager.sol";

import {D18} from "../../misc/types/D18.sol";

import {PoolId} from "../../core/types/PoolId.sol";
import {ISpoke} from "../../core/spoke/interfaces/ISpoke.sol";
import {ShareClassId} from "../../core/types/ShareClassId.sol";
import {ISpokeRegistry} from "../../core/spoke/interfaces/ISpokeRegistry.sol";
import {IManagerCallFromHub} from "../../core/utils/interfaces/IManagerCall.sol";

import {ISubsidyManager} from "../../utils/interfaces/ISubsidyManager.sol";

//----------------------------------------------------------------------------------------------
// Deposit Manager Interfaces
//----------------------------------------------------------------------------------------------

interface IDepositManager {
    /// @notice Processes owner's asset deposit after the epoch has been executed on the corresponding CP instance and
    ///         the deposit order has been successfully processed (partial fulfillment possible).
    ///         Shares are transferred from the escrow to the receiver. Amount of shares is computed based of the amount
    ///         of assets and the owner's share price.
    /// @dev    The assets required to fulfill the deposit are already locked in escrow upon calling requestDeposit.
    ///         The shares required to fulfill the deposit have already been minted and transferred to the escrow on
    ///         fulfillDepositRequest.
    ///         Both the owner and the receiver have to pass all the share token restrictions: the owner
    ///         has to pass them for the claimed amount as well (mirrors `maxMint`).
    function deposit(IBaseVault vault, uint256 assets, address receiver, address owner)
        external
        returns (uint256 shares);

    /// @notice Processes owner's share mint after the epoch has been executed on the corresponding CP instance and the
    ///         deposit order has been successfully processed (partial fulfillment possible).
    ///         Shares are transferred from the escrow to the receiver. Amount of assets is computed based of the amount
    ///         of shares and the owner's share price.
    /// @dev    The assets required to fulfill the mint are already locked in escrow upon calling requestDeposit.
    ///         The shares required to fulfill the mint have already been minted and transferred to the escrow on
    ///         fulfillDepositRequest.
    ///         Both the owner and the receiver have to pass all the share token restrictions: the owner
    ///         has to pass them for the claimed amount as well (mirrors `maxMint`).
    function mint(IBaseVault vault, uint256 shares, address receiver, address owner) external returns (uint256 assets);

    /// @notice Returns the max amount of assets based on the unclaimed amount of shares after at least one successful
    ///         deposit order fulfillment on the corresponding CP instance.
    function maxDeposit(IBaseVault vault, address user) external view returns (uint256);

    /// @notice Returns the max amount of shares a user can claim after at least one successful deposit order
    ///         fulfillment on the corresponding CP instance.
    function maxMint(IBaseVault vault, address user) external view returns (uint256 shares);
}

interface ISyncDepositManager is IDepositManager {
    function previewDeposit(IBaseVault vault, address sender, uint256 assets) external view returns (uint256);
    function previewMint(IBaseVault vault, address sender, uint256 shares) external view returns (uint256);
}

interface IAsyncDepositManager is IDepositManager, IBaseRequestManager {
    /// @notice Requests assets deposit. Vaults have to request investments from Centrifuge before
    ///         shares can be minted. The deposit requests are added to the order book
    ///         on the corresponding CP instance. Once the next epoch is executed on the corresponding CP instance,
    ///         vaults can proceed with share payouts in case the order got fulfilled.
    /// @dev    The assets required to fulfill the deposit request have to be locked and are transferred from the
    ///         owner to the escrow, even though the share payout can only happen after epoch execution.
    ///         The receiver becomes the owner of deposit request fulfillment.
    /// @param  source Deprecated
    function requestDeposit(IBaseVault vault, uint256 assets, address receiver, address owner, address source)
        external
        returns (bool);

    /// @notice Requests the cancellation of a pending deposit request. Vaults have to request the
    ///         cancellation of outstanding requests from Centrifuge before actual assets can be unlocked and
    ///         transferred to the owner.
    ///         While users have outstanding cancellation requests no new deposit requests can be submitted.
    ///         Once the next epoch is executed on the corresponding CP instance, vaults can proceed with asset payouts
    ///         if orders could be cancelled successfully.
    /// @dev    The cancellation request might fail in case the pending deposit order already got fulfilled on
    ///         Centrifuge.
    /// @param  source Deprecated
    function cancelDepositRequest(IBaseVault vault, address owner, address source) external;

    /// @notice Processes owner's deposit request cancellation after the epoch has been executed on the corresponding CP
    ///         instance and the deposit order cancellation has been successfully processed (partial fulfillment
    ///         possible).
    ///         Assets are transferred from the escrow to the receiver.
    /// @dev    The assets required to fulfill the claim have already been reserved for the owner in escrow on
    ///         fulfillDepositRequest with non-zero cancelled asset amount value.
    function claimCancelDepositRequest(IBaseVault vault, address receiver, address owner)
        external
        returns (uint256 assets);

    /// @notice Indicates whether a user has pending deposit requests and returns the total deposit request asset
    ///         request value.
    function pendingDepositRequest(IBaseVault vault, address user) external view returns (uint256 assets);

    /// @notice Indicates whether a user has pending deposit request cancellations.
    function pendingCancelDepositRequest(IBaseVault vault, address user) external view returns (bool isPending);

    /// @notice Indicates whether a user has claimable deposit request cancellation and returns the total claim
    ///         value in assets. Returns 0 while the share token restrictions block the user, matching what
    ///         {claimCancelDepositRequest} would do.
    function claimableCancelDepositRequest(IBaseVault vault, address user) external view returns (uint256 assets);
}

//----------------------------------------------------------------------------------------------
// Redeem Manager Interfaces
//----------------------------------------------------------------------------------------------

interface IRedeemManager {
    event TriggerRedeemRequest(
        uint64 indexed poolId,
        bytes16 indexed scId,
        address user,
        address indexed asset,
        uint256 tokenId,
        uint128 shares
    );

    /// @notice Processes owner's share redemption after the epoch has been executed on the corresponding CP instance
    ///         and the redeem order has been successfully processed (partial fulfillment possible).
    ///         Assets are transferred from the escrow to the receiver. Amount of assets is computed based of the amount
    ///         of shares and the owner's share price.
    /// @dev    The shares required to fulfill the redemption were already locked in escrow on requestRedeem and burned
    ///         on fulfillRedeemRequest.
    ///         The assets required to fulfill the redemption have already been reserved in escrow on
    ///         fulfillRedeemtRequest.
    function redeem(IBaseVault vault, uint256 shares, address receiver, address owner) external returns (uint256 assets);

    /// @notice Processes owner's asset withdrawal after the epoch has been executed on the corresponding CP instance
    ///         and the redeem order has been successfully processed (partial fulfillment possible).
    ///         Assets are transferred from the escrow to the receiver. Amount of shares is computed based of the amount
    ///         of shares and the owner's share price.
    /// @dev    The shares required to fulfill the withdrawal were already locked in escrow on requestRedeem and burned
    ///         on fulfillRedeemRequest.
    ///         The assets required to fulfill the withdrawal have already been reserved in escrow on
    ///         fulfillRedeemtRequest.
    function withdraw(IBaseVault vault, uint256 assets, address receiver, address owner)
        external
        returns (uint256 shares);

    /// @notice Returns the max amount of shares based on the unclaimed number of assets after at least one successful
    ///         redeem order fulfillment on the corresponding CP instance.
    function maxRedeem(IBaseVault vault, address user) external view returns (uint256 shares);

    /// @notice Returns the max amount of assets a user can claim after at least one successful redeem order fulfillment
    ///         on the corresponding CP instance.
    function maxWithdraw(IBaseVault vault, address user) external view returns (uint256 assets);
}

interface IAsyncRedeemManager is IRedeemManager, IBaseRequestManager {
    /// @notice Requests share redemption. Vaults have to request redemptions
    ///         from Centrifuge before actual asset payouts can be done. The redemption
    ///         requests are added to the order book on the corresponding CP instance. Once the next epoch is
    ///         executed on the corresponding CP instance, vaults can proceed with asset payouts
    ///         in case the order got fulfilled.
    /// @dev    The shares required to fulfill the redemption request have to be locked and are transferred from the
    ///         owner to the escrow, even though the asset payout can only happen after epoch execution.
    ///         The receiver becomes the owner of redeem request fulfillment.
    /// @param  source Deprecated
    /// @param  transfer Deprecated and ignored (kept for ABI compatibility); shares are always transferred
    ///         to the pool escrow by this manager
    function requestRedeem(
        IBaseVault vault,
        uint256 shares,
        address receiver,
        address owner,
        address source,
        bool transfer
    ) external returns (bool);

    /// @notice Requests the cancellation of an pending redeem request. Vaults have to request the
    ///         cancellation of outstanding requests from Centrifuge before actual shares can be unlocked and
    ///         transferred to the owner.
    ///         While users have outstanding cancellation requests no new redeem requests can be submitted (exception:
    ///         trigger through governance).
    ///         Once the next epoch is executed on the corresponding CP instance, vaults can proceed with share payouts
    ///         if the orders could be cancelled successfully.
    /// @dev    The cancellation request might fail in case the pending redeem order already got fulfilled on
    ///         Centrifuge.
    function cancelRedeemRequest(IBaseVault vault, address owner, address source) external;

    /// @notice Processes owner's redeem request cancellation after the epoch has been executed on the corresponding CP
    ///         instance and the redeem order cancellation has been successfully processed (partial fulfillment
    ///         possible).
    ///         Shares are transferred from the escrow to the receiver.
    /// @dev    The shares required to fulfill the claim have already been reserved for the owner in escrow on
    ///         fulfillRedeemRequest with non-zero cancelled share amount value.
    ///         Both the owner and the receiver have to pass all the share token restrictions: the owner
    ///         has to pass them for the claimed amount as well (mirrors `claimableCancelRedeemRequest`).
    function claimCancelRedeemRequest(IBaseVault vault, address receiver, address owner)
        external
        returns (uint256 shares);

    /// @notice Indicates whether a user has pending redeem requests and returns the total share request value.
    function pendingRedeemRequest(IBaseVault vault, address user) external view returns (uint256 shares);

    /// @notice Indicates whether a user has pending redeem request cancellations.
    function pendingCancelRedeemRequest(IBaseVault vault, address user) external view returns (bool isPending);

    /// @notice Indicates whether a user has claimable redeem request cancellation and returns the total claim
    ///         value in shares. Returns 0 while the share token restrictions block the escrow-to-user leg,
    ///         matching what {claimCancelRedeemRequest} would do.
    function claimableCancelRedeemRequest(IBaseVault vault, address user) external view returns (uint256 shares);
}

//----------------------------------------------------------------------------------------------
// Price Data Structures
//----------------------------------------------------------------------------------------------

/// @dev Solely used locally as protection against stack-too-deep
struct Prices {
    /// @dev Price of 1 asset unit per share unit
    D18 assetPerShare;
    /// @dev Price of 1 pool unit per asset unit
    D18 poolPerAsset;
    /// @dev Price of 1 pool unit per share unit
    D18 poolPerShare;
}

//----------------------------------------------------------------------------------------------
// Sync Manager Interfaces
//----------------------------------------------------------------------------------------------

interface ISyncDepositValuation {
    /// @notice Returns the pool price per share for a given pool and share class, asset, and asset id.
    // The provided price is defined as POOL_UNIT/SHARE_UNIT.
    ///
    /// @param poolId The pool id
    /// @param scId The share class id
    /// @return price The pool price per share
    function pricePoolPerShare(PoolId poolId, ShareClassId scId) external view returns (D18 price);
}

interface ISyncManager is ISyncDepositManager, ISyncDepositValuation, IManagerCallFromHub {
    event SetValuation(PoolId indexed poolId, ShareClassId indexed scId, address valuation);
    event SetMaxReserve(
        PoolId indexed poolId, ShareClassId indexed scId, address asset, uint256 tokenId, uint128 maxReserve
    );
    event File(bytes32 indexed what, address data);

    error NotEnvoy();
    error UnexpectedValue();
    error ExceedsMaxDeposit();
    error FileUnrecognizedParam();
    error ExceedsMaxMint();
    error ShareTokenDoesNotExist();
    error SecondaryManagerDoesNotExist();
    error UnknownTrustedCall();

    enum TrustedCall {
        Valuation,
        MaxReserve
    }

    /// @notice The Envoy that routes policy-supervised valuation/max-reserve updates
    function envoy() external view returns (address);

    /// @notice Updates contract parameters of type address.
    /// @param what The bytes32 representation of 'spoke', 'spokeRegistry' or 'envoy'.
    /// @param data The new contract address.
    function file(bytes32 what, address data) external;

    /// @notice Converts the assets value to share decimals.
    function convertToShares(IBaseVault vault, uint256 _assets) external view returns (uint256 shares);

    /// @notice Converts the shares value to assets decimals.
    function convertToAssets(IBaseVault vault, uint256 _shares) external view returns (uint256 assets);

    /// @notice Sets the valuation for a specific pool and share class.
    ///
    /// @param poolId The id of the pool
    /// @param scId The id of the share class
    /// @param valuation The address of the valuation contract
    function setValuation(PoolId poolId, ShareClassId scId, address valuation) external;

    /// @notice Sets the max reserve for a specific pool, share class and asset.
    ///
    /// @param poolId The id of the pool
    /// @param scId The id of the share class
    /// @param asset The address of the asset
    /// @param tokenId The asset token id, i.e. 0 for ERC20, or the token id for ERC6909
    /// @param maxReserve The amount of maximum reserve
    function setMaxReserve(PoolId poolId, ShareClassId scId, address asset, uint256 tokenId, uint128 maxReserve)
        external;

    /// @notice Manages share token and asset balances, including minting, burning, and escrow transfers
    function spoke() external view returns (ISpoke);

    /// @notice Stores pool, share class, asset, vault, and price state for the spoke side
    function spokeRegistry() external view returns (ISpokeRegistry);

    /// @notice Price source contract used for sync deposit pricing on a given pool and share class
    function valuation(PoolId poolId, ShareClassId scId) external view returns (ISyncDepositValuation);

    /// @notice Maximum asset amount the escrow will accept for a given pool, share class, and asset
    function maxReserve(PoolId poolId, ShareClassId scId, address asset, uint256 tokenId)
        external
        view
        returns (uint128);
}

//----------------------------------------------------------------------------------------------
// Async Investment Data Structures
//----------------------------------------------------------------------------------------------

/// @dev Vault requests and deposit/redeem bookkeeping per user
struct AsyncInvestmentState {
    /// @dev Shares that can be claimed using `mint()`
    uint128 maxMint;
    /// @dev Assets that can be claimed using `withdraw()`
    uint128 maxWithdraw;
    /// @dev Weighted average price of deposits, used to convert maxMint to maxDeposit
    /// @dev Represents priceAssetPerShare, i.e. ASSET_UNIT/SHARE_UNIT
    D18 depositPrice;
    /// @dev Weighted average price of redemptions, used to convert maxWithdraw to maxRedeem
    /// @dev Represents priceAssetPerShare, i.e. ASSET_UNIT/SHARE_UNIT
    D18 redeemPrice;
    /// @dev Remaining deposit request in assets
    uint128 pendingDepositRequest;
    /// @dev Remaining redeem request in shares
    uint128 pendingRedeemRequest;
    /// @dev Assets that can be claimed using `claimCancelDepositRequest()`
    uint128 claimableCancelDepositRequest;
    /// @dev Shares that can be claimed using `claimCancelRedeemRequest()`
    uint128 claimableCancelRedeemRequest;
    /// @dev Indicates whether the depositRequest was requested to be cancelled
    bool pendingCancelDepositRequest;
    /// @dev Indicates whether the redeemRequest was requested to be cancelled
    bool pendingCancelRedeemRequest;
}

//----------------------------------------------------------------------------------------------
// Async Request Manager Interface
//----------------------------------------------------------------------------------------------

/// @dev Reservation reason for deposit flows
bytes32 constant REASON_DEPOSIT = bytes32(uint256(1));
/// @dev Reservation reason for redeem flows
bytes32 constant REASON_REDEEM = bytes32(uint256(2));

interface IAsyncRequestManager is IAsyncDepositManager, IAsyncRedeemManager {
    error ExceedsMaxDeposit();
    error AssetMismatch();
    error ZeroAmountNotAllowed();
    error TransferNotAllowed();
    error CancellationIsPending();
    error NoPendingRequest();
    error ShareTokenAmountIsZero();
    error FailedRedeemRequest();
    error ExceedsDepositLimits();
    error ShareTokenTransferFailed();
    error ExceedsMaxRedeem();
    error ExceedsRedeemLimits();
    error VaultNotLinked();
    error NotAVault();

    /// @notice Returns the investment state
    /// @dev    Keyed per vault, while the hub aggregates the order it belongs to per pool, share class,
    ///         asset and investor: vaults linked to one such tuple share a hub order but keep separate
    ///         local amounts. Fulfillments settle on the vault the share token's pointer names, so
    ///         requests are expected to originate there. One sent from another linked vault joins the
    ///         shared order and is settled elsewhere, leaving that vault's pending amount stale;
    ///         cancelling it then sets the pending-cancellation flag with nothing left for the hub to
    ///         cancel, so no callback ever clears it and that vault stays blocked for that investor until
    ///         the pool points back at it and force-cancels a fresh order. The position itself stays
    ///         claimable on the pointed-at vault.
    function investments(IBaseVault vaultAddr, address investor)
        external
        view
        returns (
            uint128 maxMint,
            uint128 maxWithdraw,
            D18 depositPrice,
            D18 redeemPrice,
            uint128 pendingDepositRequest,
            uint128 pendingRedeemRequest,
            uint128 claimableCancelDepositRequest,
            uint128 claimableCancelRedeemRequest,
            bool pendingCancelDepositRequest,
            bool pendingCancelRedeemRequest
        );

    /// @notice Manages share token and asset balances, including minting, burning, and escrow transfers
    function spoke() external view returns (ISpoke);

    /// @notice Stores pool, share class, asset, vault, and price state for the spoke side
    function spokeRegistry() external view returns (ISpokeRegistry);

    /// @notice Manages gas subsidies for cross-chain message costs, funded per-pool
    function subsidyManager() external view returns (ISubsidyManager);
}

src/vaults/interfaces/IVaultRouter.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {IBaseVault} from "./IBaseVault.sol";
import {IAsyncVault} from "./IAsyncVault.sol";

import {IMulticall} from "../../misc/interfaces/IMulticall.sol";

import {PoolId} from "../../core/types/PoolId.sol";
import {ISpoke} from "../../core/spoke/interfaces/ISpoke.sol";
import {ShareClassId} from "../../core/types/ShareClassId.sol";
import {ISpokeRegistry} from "../../core/spoke/interfaces/ISpokeRegistry.sol";

import {BaseSyncDepositVault} from "../BaseVaults.sol";

interface IVaultRouter is IMulticall {
    //----------------------------------------------------------------------------------------------
    // Events
    //----------------------------------------------------------------------------------------------

    event LockDepositRequest(
        IBaseVault indexed vault, address indexed controller, address indexed owner, address sender, uint256 amount
    );
    event UnlockDepositRequest(IBaseVault indexed vault, address indexed controller, address indexed receiver);
    event ExecuteLockedDepositRequest(IBaseVault indexed vault, address indexed controller, address sender);

    error InvalidOwner();
    error NoLockedBalance();
    error NoLockedRequest();
    error ZeroBalance();
    error InvalidSender();
    error NonSyncDepositVault();
    error NonAsyncVault();

    //----------------------------------------------------------------------------------------------
    // Manage permissionless claiming
    //----------------------------------------------------------------------------------------------

    /// @notice Enable permissionless claiming
    /// @dev    After this is called, anyone can claim tokens to msg.sender.
    ///         Even any requests submitted directly to the vault (not through the VaultRouter) will be
    ///         permissionlessly claimable through the VaultRouter, until `disable()` is called.
    function enable(IBaseVault vault) external payable;

    /// @notice Disable permissionless claiming
    function disable(IBaseVault vault) external payable;

    //----------------------------------------------------------------------------------------------
    // Deposit
    //----------------------------------------------------------------------------------------------

    /// @notice Check `IERC7540Deposit.requestDeposit`.
    /// @param  vault The vault to deposit into
    /// @param  amount Check @param IERC7540Deposit.requestDeposit.assets
    /// @param  controller Check @param IERC7540Deposit.requestDeposit.controller
    /// @param  owner Check @param IERC7540Deposit.requestDeposit.owner
    function requestDeposit(IAsyncVault vault, uint256 amount, address controller, address owner) external payable;

    /// @notice Check `IERC4626.deposit`.
    /// @dev    The vault sees the router as the depositor, so the router checks that msg.sender is permissioned on
    ///         the vault, as a direct deposit would.
    /// @param  vault The vault to deposit into
    /// @param  assets Check @param IERC4626.deposit.assets
    /// @param  receiver Check @param IERC4626.deposit.receiver
    /// @param  owner User from which to transfer the assets, either msg.sender or the VaultRouter
    function deposit(BaseSyncDepositVault vault, uint256 assets, address receiver, address owner) external payable;

    /// @notice Check IERC7540Deposit.mint
    /// @param  vault Address of the vault
    /// @param  receiver Check IERC7540Deposit.mint.receiver
    /// @param  controller Check IERC7540Deposit.mint.owner
    function claimDeposit(IAsyncVault vault, address receiver, address controller) external payable;

    /// @notice Check `IERC7887Deposit.cancelDepositRequest`.
    /// @param  vault The vault where the deposit was initiated
    function cancelDepositRequest(IAsyncVault vault) external payable;

    /// @notice Check IERC7887Deposit.claimCancelDepositRequest
    ///
    /// @param  vault Address of the vault
    /// @param  receiver Check  IERC7887Deposit.claimCancelDepositRequest.receiver
    /// @param  controller Check  IERC7887Deposit.claimCancelDepositRequest.controller
    function claimCancelDepositRequest(IAsyncVault vault, address receiver, address controller) external payable;

    //----------------------------------------------------------------------------------------------
    // Redeem
    //----------------------------------------------------------------------------------------------

    /// @notice Check `IERC7540Redeem.requestRedeem`.
    /// @param  vault The vault to deposit into
    /// @param  amount Check @param IERC7540Redeem.requestRedeem.shares
    /// @param  controller Check @param IERC7540Redeem.requestRedeem.controller
    /// @param  owner Check @param IERC7540Redeem.requestRedeem.owner
    function requestRedeem(IAsyncVault vault, uint256 amount, address controller, address owner) external payable;

    /// @notice Check IERC7575.withdraw
    /// @dev    If the underlying vault asset is a wrapped one,
    ///         `VaultRouter.unwrap` is called and the unwrapped
    ///         asset is sent to the receiver
    /// @param  vault Address of the vault
    /// @param  receiver Check IERC7575.withdraw.receiver
    /// @param  controller Check IERC7575.withdraw.owner
    function claimRedeem(IBaseVault vault, address receiver, address controller) external payable;

    /// @notice Check `IERC7887Redeem.cancelRedeemRequest`.
    /// @param  vault The vault where the deposit was initiated
    function cancelRedeemRequest(IAsyncVault vault) external payable;

    /// @notice Check IERC7887Redeem.claimableCancelRedeemRequest
    ///
    /// @param  vault Address of the vault
    /// @param  receiver Check  IERC7887Redeem.claimCancelRedeemRequest.receiver
    /// @param  controller Check  IERC7887Redeem.claimCancelRedeemRequest.controller
    function claimCancelRedeemRequest(IAsyncVault vault, address receiver, address controller) external payable;

    //----------------------------------------------------------------------------------------------
    // Cross-chain transfers
    //----------------------------------------------------------------------------------------------

    /// @notice Intended to be used in a batch with `deposit` or `claimDeposit`.
    ///         The preceding vault call's `receiver` must be set to `address(this)` (the router),
    ///         not this function's `receiver` parameter (which is the destination bytes32 address on the
    ///         remote chain). `owner` must be either `msg.sender` or `address(this)` (the router itself,
    ///         for the batched case where the router holds the shares as an intermediate step).
    function crosschainTransferShares(
        BaseSyncDepositVault vault,
        uint128 shares,
        uint16 centrifugeId,
        bytes32 receiver,
        address owner,
        uint128 extraGasLimit,
        uint128 remoteExtraGasLimit,
        address refund
    ) external payable;

    //----------------------------------------------------------------------------------------------
    // ERC20 permit
    //----------------------------------------------------------------------------------------------

    /// @notice Check IERC20.permit
    function permit(address asset, address spender, uint256 assets, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
        external
        payable;

    //----------------------------------------------------------------------------------------------
    // View Methods
    //----------------------------------------------------------------------------------------------

    /// @notice Check ISpoke.getVault
    function getVault(PoolId poolId, ShareClassId scId, address asset) external view returns (address);

    /// @notice Called to check if `user` has permissions on `vault` to execute requests
    ///
    /// @param vault Address of the `vault` the `user` wants to operate on
    /// @param user Address of the `user` that will operates on the `vault`
    /// @return Whether `user` has permissions to operate on `vault`
    function hasPermissions(IBaseVault vault, address user) external view returns (bool);

    /// @notice Returns whether the controller has called `enable()` for the given `vault`
    function isEnabled(IBaseVault vault, address controller) external view returns (bool);

    /// @notice Spoke-side entry point for this chain's pool and share class operations
    function spoke() external view returns (ISpoke);

    /// @notice Stores pool, share class, asset, price and vault state for the spoke side
    function spokeRegistry() external view returns (ISpokeRegistry);
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": true
  },
  "libraries": {},
  "optimizer": {
    "runs": 1,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/halmos-cheatcodes/src/",
    "@chimera/=lib/chimera/src/",
    "safe-utils/=lib/safe-utils/src/",
    "safe-smart-account/=lib/safe-utils/lib/safe-smart-account/contracts/",
    "solidity-http/=lib/safe-utils/lib/solidity-http/src/",
    "solidity-stringutils/=lib/safe-utils/lib/solidity-stringutils/src/",
    "@recon/=lib/setup-helpers/src/",
    "chimera/=lib/chimera/src/",
    "ds-test/=lib/chimera/lib/forge-std/lib/ds-test/src/",
    "setup-helpers/=lib/setup-helpers/src/",
    "src/=src/",
    "test/=test/",
    "createx-forge/=lib/createx-forge/",
    "create3-gate/=lib/create3-gate/",
    "lib/create3-gate/:createx-forge/script/=script/utils/createx/",
    "enso-weiroll/=lib/enso-weiroll/contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.