Skip to content
Verified contractPartialBUSL-1.1

OpsGuardian

Address0x8077de93d12413aeff5ea51f832aa839cc4be666
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,888
Creation transaction
0x90a4fffe16…89c264e160

src/admin/OpsGuardian.sol

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

import {ISafe} from "./interfaces/ISafe.sol";
import {ICreatePool} from "./interfaces/ICreatePool.sol";
import {IGasService} from "./interfaces/IGasService.sol";
import {IOpsGuardian} from "./interfaces/IOpsGuardian.sol";
import {IAdapterWiring} from "./interfaces/IAdapterWiring.sol";

import {PoolId} from "../core/types/PoolId.sol";
import {AssetId} from "../core/types/AssetId.sol";
import {IAdapter} from "../core/messaging/interfaces/IAdapter.sol";
import {IGateway} from "../core/messaging/interfaces/IGateway.sol";
import {IMultiAdapter} from "../core/messaging/interfaces/IMultiAdapter.sol";

import {ITokenBridge} from "../bridge/interfaces/ITokenBridge.sol";

/// @title  OpsGuardian
/// @notice This contract manages operational aspects of the protocol including adapter configuration,
///         network wiring, and pool creation.
contract OpsGuardian is IOpsGuardian {
    PoolId public constant GLOBAL_POOL = PoolId.wrap(0);
    uint16 public constant MAINNET_CENTRIFUGE_ID = 1;

    ISafe public opsSafe;
    ICreatePool public hub;
    ITokenBridge public tokenBridge;
    IMultiAdapter public multiAdapter;

    constructor(ISafe opsSafe_, ICreatePool hub_, ITokenBridge tokenBridge_, IMultiAdapter multiAdapter_) {
        opsSafe = opsSafe_;
        hub = hub_;
        tokenBridge = tokenBridge_;
        multiAdapter = multiAdapter_;
    }

    modifier onlySafe() {
        require(msg.sender == address(opsSafe), NotTheAuthorizedSafe());
        _;
    }

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

    /// @inheritdoc IOpsGuardian
    function file(bytes32 what, address data) external onlySafe {
        if (what == "opsSafe") opsSafe = ISafe(data);
        else if (what == "hub") hub = ICreatePool(data);
        else if (what == "tokenBridge") tokenBridge = ITokenBridge(data);
        else if (what == "multiAdapter") multiAdapter = IMultiAdapter(data);
        else revert FileUnrecognizedParam();
        emit File(what, data);
    }

    /// @inheritdoc IOpsGuardian
    function setGasService(IGasService gasService) external onlySafe {
        IGateway(address(multiAdapter.gateway())).file("messageGas", address(gasService));
        multiAdapter.file("messageGas", address(gasService));
    }

    //----------------------------------------------------------------------------------------------
    // Adapter Management
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IOpsGuardian
    function setAdapters(uint16 centrifugeId, IAdapter[] calldata adapters, uint8 threshold) external onlySafe {
        // Not redundant with the bootstrap check below. That one still permits a first configuration, and
        // for this one lane even the first is different in kind: ScheduleUpgrade is accepted only from
        // mainnet (MessageLib.messageSourceCentrifugeId) and lands on Root.scheduleRely
        // (MessageProcessor). Whoever installs this lane's first set can forge it. Elsewhere a compromised
        // first set buys a forged RegisterAsset; here it buys Root, so bringing this lane up is a spell.
        require(centrifugeId != MAINNET_CENTRIFUGE_ID, CannotSetAdaptersForMainnet());
        require(centrifugeId != multiAdapter.localCentrifugeId(), CannotSetAdaptersForLocalChain());

        // MultiAdapter permits an empty set (quorum 0, threshold 0). Installing one would still bump the
        // session, and the bootstrap check below would then refuse the correction: the lane would be dead
        // and only Root could revive it. Refuse it here instead.
        require(threshold > 0, EmptyAdapterSet());

        // Bootstrap only. The global set carries RegisterAsset and a pool's first SetPoolAdapters on a
        // lane, so a safe that could replace a live one could forge either; replacing it is Root's, over
        // the timelock. Containment does not wait on that: {blockSession} is immediate and is still ours.
        uint16 targetSessionId = multiAdapter.nextActiveSessionId(centrifugeId, GLOBAL_POOL);
        require(targetSessionId == 1, AdaptersAlreadySet());

        multiAdapter.setAdapters(centrifugeId, GLOBAL_POOL, adapters, threshold, targetSessionId);
    }

    /// @inheritdoc IOpsGuardian
    function wire(IAdapterWiring adapter, uint16 centrifugeId, bytes memory data) external onlySafe {
        require(centrifugeId != multiAdapter.localCentrifugeId(), CannotWireLocalChain());
        require(!adapter.isWired(centrifugeId, data), AdapterAlreadyWired());

        adapter.wire(centrifugeId, data);
    }

    /// @inheritdoc IOpsGuardian
    function blockSession(uint16 centrifugeId, uint16 sessionId) external onlySafe {
        multiAdapter.blockSession(centrifugeId, GLOBAL_POOL, sessionId);
    }

    //----------------------------------------------------------------------------------------------
    // Pool Management
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IOpsGuardian
    function createPool(PoolId poolId, address admin, AssetId currency) external onlySafe {
        hub.createPool(poolId, admin, currency);
    }

    //----------------------------------------------------------------------------------------------
    // Bridge Management
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IOpsGuardian
    function fileTokenBridgeCentrifugeId(uint256 evmChainId, uint16 centrifugeId) external onlySafe {
        require(tokenBridge.chainIdToCentrifugeId(evmChainId) == 0, CentrifugeIdAlreadySet());
        tokenBridge.file("centrifugeId", evmChainId, centrifugeId);
    }
}

src/admin/interfaces/IAdapterGasService.sol

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

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

/// @title  IAdapterGasService
/// @notice What an adapter needs from the gas service, on top of the message properties the core reads.
/// @dev    Adapters reach the gas service through `MultiAdapter.messageGas()`, which is typed as
///         the core interface and must stay that way: the core has no business knowing that a receive
///         path has a cost. Adapters cast to this, which is where that knowledge belongs, because the
///         gas service is not a core contract and may assume things about the adapters it prices.
interface IAdapterGasService is IMessageGas {
    error UnknownAdapter();

    /// @notice Gas an adapter must reserve for its own receive path on `centrifugeId`, on top of the
    ///         message gas limit it is asked to deliver. In gas, not in the native token `estimate` quotes.
    /// @dev    An adapter names itself and nothing else: what its receive path consumes and what each
    ///         chain charges for it are both held by the gas service, so a repricing, a rebenchmark or a
    ///         new chain never reaches adapter code. `adapter` is a short-string id, the same way
    ///         {IMultiAdapter-file} names a dependency, so adapters can be added or retired without
    ///         holding an order or leaving a retired index behind.
    function receiveCost(uint16 centrifugeId, bytes32 adapter) external view returns (uint128);
}

src/admin/interfaces/IAdapterWiring.sol

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

/// @title  IAdapterWiring
/// @notice Interface for cross-chain bridge adapters that support wiring configuration
/// @dev    Only bridge adapters implement this interface.
///         Local adapters (e.g. StandbyAdapter) do not support wiring operations.
interface IAdapterWiring {
    /// @notice Wire the adapter to a remote chain
    /// @dev    If this is rewiring a previously wired centrifugeId, it might be necessary
    ///         to call first with an empty destination for the previous configuration, to reset.
    /// @param centrifugeId The chain ID to wire to
    /// @param data ABI-encoded adapter-specific configuration data
    function wire(uint16 centrifugeId, bytes memory data) external;

    /// @notice Whether `wire(centrifugeId, data)` would overwrite an existing binding
    /// @dev    `wire()` writes two mappings: the destination for `centrifugeId` and the source for the bridge
    ///         id carried in `data`. This is true when either is already set, so a first-time wire can neither
    ///         re-point a chain nor steal a bridge id that another chain's inbound messages arrive under. False
    ///         again after a reset (a `wire()` with an empty destination). The OpsGuardian may only wire
    ///         adapters for which this is false.
    /// @param centrifugeId The chain ID to check
    /// @param data ABI-encoded adapter-specific configuration data, as `wire()` would receive it
    function isWired(uint16 centrifugeId, bytes memory data) external view returns (bool);
}

src/admin/interfaces/ICreatePool.sol

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

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

interface ICreatePool {
    /// @notice Creates a new pool
    /// @param poolId The unique identifier for the pool
    /// @param admin The address that will be the pool administrator
    /// @param currency The pool currency, usually an AssetId identifying by a ISO4217 code
    function createPool(PoolId poolId, address admin, AssetId currency) external payable;
}

src/admin/interfaces/IGasService.sol

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

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

/// @title  IGasService
/// @notice Interface for estimating gas costs for cross-chain messages
/// @dev    Provides gas cost estimates for each message type in the protocol
interface IGasService is IAdapterGasService {
    error InvalidMessageType();

    /// @notice Packed uint8 array of per-chain block gas limits (in millions), indexed by centrifugeId (first 32 chains)
    function txLimitsPerCentrifugeId() external view returns (uint256);

    function scheduleUpgrade() external view returns (uint128);
    function cancelUpgrade() external view returns (uint128);
    function registerAsset() external view returns (uint128);
    function setPoolAdapters() external view returns (uint128);
    function request() external view returns (uint128);
    function notifyPool() external view returns (uint128);
    function notifyShareClass() external view returns (uint128);
    function notifyPricePoolPerShare() external view returns (uint128);
    function notifyPricePoolPerAsset() external view returns (uint128);
    function notifyShareMetadata() external view returns (uint128);
    function initiateTransferShares() external view returns (uint128);
    function executeTransferShares() external view returns (uint128);
    function updateRestriction() external view returns (uint128);
    function managerCallFromHub() external view returns (uint128);
    function requestCallback() external view returns (uint128);
    function updateVaultDeployAndLink() external view returns (uint128);
    function updateVaultLink() external view returns (uint128);
    function updateVaultUnlink() external view returns (uint128);
    function setRequestManager() external view returns (uint128);
    function setPolicy() external view returns (uint128);
    function authorizeSpokeCall() external view returns (uint128);
    function unauthorizeSpokeCall() external view returns (uint128);
    function updateManager() external view returns (uint128);
    function updateAssets() external view returns (uint128);
    function updateShares() external view returns (uint128);
    function managerCallFromSpoke() external view returns (uint128);
}

src/admin/interfaces/IOpsGuardian.sol

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

import {ISafe} from "./ISafe.sol";
import {ICreatePool} from "./ICreatePool.sol";
import {IGasService} from "./IGasService.sol";
import {IAdapterWiring} from "./IAdapterWiring.sol";

import {PoolId} from "../../core/types/PoolId.sol";
import {AssetId} from "../../core/types/AssetId.sol";
import {IAdapter} from "../../core/messaging/interfaces/IAdapter.sol";
import {IMultiAdapter} from "../../core/messaging/interfaces/IMultiAdapter.sol";

import {ITokenBridge} from "../../bridge/interfaces/ITokenBridge.sol";

interface IOpsGuardian {
    error NotTheAuthorizedSafe();
    error FileUnrecognizedParam();
    error CannotSetAdaptersForLocalChain();
    error CannotSetAdaptersForMainnet();
    error AdaptersAlreadySet();
    error EmptyAdapterSet();
    error CannotWireLocalChain();
    error CentrifugeIdAlreadySet();
    error AdapterAlreadyWired();

    event File(bytes32 indexed what, address data);

    /// @notice Install the global adapter set for a remote network, once
    /// @dev Reverts if centrifugeId matches the local chain or the hub chain
    /// @dev Does not trigger cross-chain message - local operation only
    /// @dev Bootstrap only: reverts once the network has a set, so this installs one and never replaces one.
    ///      Two things ride the global set without requiring a mainnet source: RegisterAsset, and a pool's
    ///      first SetPoolAdapters on a lane, which falls back to global while that pool has no set of its
    ///      own (MessageLib.routePoolId). A safe that could replace a live set could therefore install a
    ///      one-of-one adapter of its own and forge either. Replacing a live set is Root's, over the
    ///      timelock. Containment is not: {blockSession} takes a bad set offline immediately and remains ours
    /// @param centrifugeId Target chain ID to configure adapters on
    /// @param adapters Array of adapter contract addresses
    /// @param threshold Minimum number of adapters that must agree
    function setAdapters(uint16 centrifugeId, IAdapter[] calldata adapters, uint8 threshold) external;

    /// @notice Wire an adapter to a remote chain it is not yet wired to
    /// @dev First-time only, per adapter: reverts once `adapter.isWired(centrifugeId, data)` holds, that is when
    ///      the chain already has a destination or the bridge id in `data` already serves another chain, so a
    ///      binding that exists can only be re-pointed or reset by a spell, through Root. A newly deployed
    ///      adapter is unwired for every chain, so the OpsGuardian can still connect it to any chain.
    /// @dev Reverts if centrifugeId is the local chain, which is never a valid remote wiring target.
    /// @param adapter Address of the adapter to wire
    /// @param centrifugeId The chain ID to wire to
    /// @param data ABI-encoded adapter-specific configuration data
    function wire(IAdapterWiring adapter, uint16 centrifugeId, bytes memory data) external;

    /// @notice Mark a global-pool session as blocked, preventing its adapters from voting on messages
    /// @dev Local-only operation for fast emergency response; recovery (unblock) is performed via a Spell
    /// @param centrifugeId Target chain ID
    /// @param sessionId Session to block
    function blockSession(uint16 centrifugeId, uint16 sessionId) external;

    /// @notice Updates a contract parameter
    /// @param what Accepts a bytes32 representation of 'opsSafe', 'hub', 'tokenBridge', or 'multiAdapter'
    /// @param data New value for the parameter
    function file(bytes32 what, address data) external;

    /// @notice Updates the gas service used by the system, on both contracts that hold a reference to it
    /// @dev    Gas values only. How a message is framed and which source chain it must come from is read from
    ///         the processor and the parser, Root-filed dependencies, so this cannot weaken source-chain
    ///         authentication. Both references move together: leaving MultiAdapter on the old gas service
    ///         would have adapters pricing their receive path against a service Gateway no longer uses.
    /// @param gasService the new gas service to use
    function setGasService(IGasService gasService) external;

    /// @notice Registers a new pool
    /// @param poolId The pool identifier
    /// @param admin The admin address for the pool
    /// @param currency The currency asset ID for the pool
    function createPool(PoolId poolId, address admin, AssetId currency) external;

    /// @notice Configure TokenBridge chain ID mapping (first-time only)
    /// @param evmChainId The EVM chain ID
    /// @param centrifugeId The corresponding Centrifuge chain ID
    function fileTokenBridgeCentrifugeId(uint256 evmChainId, uint16 centrifugeId) external;

    /// @notice Return the linked operational safe
    /// @return The operational safe contract
    function opsSafe() external view returns (ISafe);

    /// @notice Hub contract called to register new pools
    function hub() external view returns (ICreatePool);

    /// @notice MultiAdapter used for adapter configuration and wiring on remote networks
    function multiAdapter() external view returns (IMultiAdapter);

    /// @notice TokenBridge used for cross-chain share token transfers
    function tokenBridge() external view returns (ITokenBridge);
}

src/admin/interfaces/ISafe.sol

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

interface ISafe {
    /// @notice Checks if an address is an owner of the safe
    /// @param signer The address to check for ownership
    /// @return True if the address is an owner, false otherwise
    function isOwner(address signer) external view returns (bool);
}

src/bridge/interfaces/ITokenBridge.sol

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

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

import {PoolId} from "../../core/types/PoolId.sol";
import {ShareClassId} from "../../core/types/ShareClassId.sol";
import {IGateway} from "../../core/messaging/interfaces/IGateway.sol";

interface ITokenBridge is IRecoverable {
    event File(bytes32 indexed what, address data);
    event File(bytes32 indexed what, uint256 evmChainId, uint16 centrifugeId);
    event UpdateGasLimits(
        PoolId indexed poolId, ShareClassId indexed scId, uint128 extraGasLimit, uint128 remoteExtraGasLimit
    );
    event Send(
        address indexed token,
        address indexed sender,
        uint256 destinationChainId,
        bytes32 receiver,
        uint256 amount,
        address refundAddress
    );

    error NotEnvoy();
    error UnexpectedValue();
    error NotBatchable();
    error FileUnrecognizedParam();
    error InvalidChainId();
    error ShareTokenDoesNotExist();

    struct GasLimits {
        uint128 extraGasLimit;
        uint128 remoteExtraGasLimit;
    }

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

    /// @notice Configure contract parameters
    /// @param what The parameter name to configure
    /// @param data The address value to set
    function file(bytes32 what, address data) external;

    /// @notice Configure chain ID mapping
    /// @param what Must be "centrifugeId"
    /// @param evmChainId The EVM chain ID
    /// @param centrifugeId The corresponding Centrifuge chain ID
    function file(bytes32 what, uint256 evmChainId, uint16 centrifugeId) external;

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

    /// @notice Send a token from chain A to chain B after approving this contract with the token
    /// @param token The address of the token sending across chains
    /// @param amount The amount of the token to send across chains
    /// @param receiver The target address that should receive the funds on the destination chain
    /// @param destinationChainId The Ethereum chain ID of the destination chain
    /// @param refundAddress The address that should receive any funds if the cross-chain gas value is too high
    /// @return Always returns empty bytes
    function send(address token, uint256 amount, bytes32 receiver, uint256 destinationChainId, address refundAddress)
        external
        payable
        returns (bytes memory);

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

    /// @notice Returns the Centrifuge chain ID of the chain this contract is deployed on
    function localCentrifugeId() external view returns (uint16);

    /// @notice Returns the envoy that routes hub-dispatched configuration updates
    function envoy() external view returns (address);

    /// @notice Returns the relayer address
    function relayer() external view returns (address);

    /// @notice Returns the gateway this contract routes transfers through
    function gateway() external view returns (IGateway);

    /// @notice Returns the Centrifuge chain ID for a given EVM chain ID
    function chainIdToCentrifugeId(uint256 evmChainId) external view returns (uint16);
}

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