Skip to content
Verified contractPartialBUSL-1.1

HubRegistry

Address0xe4d608e50ef2289d7627dbbf1e4c3845b05b182c
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,256,178
Creation transaction
0xc0dae07af7…cc0063d41c

src/core/hub/HubRegistry.sol

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

import {IHubRegistry} from "./interfaces/IHubRegistry.sol";
import {IBridgingHook} from "./interfaces/IBridgingHook.sol";
import {IHubRequestManager} from "./interfaces/IHubRequestManager.sol";

import {Auth} from "../../misc/Auth.sol";
import {MathLib} from "../../misc/libraries/MathLib.sol";
import {IERC6909Decimals} from "../../misc/interfaces/IERC6909.sol";

import {AssetId} from "../types/AssetId.sol";
import {PoolId, newPoolId} from "../types/PoolId.sol";
import {IHubPolicy} from "../utils/interfaces/IPolicy.sol";

/// @title  Hub Registry
/// @notice Registry of all known pools, currencies, and assets.
contract HubRegistry is Auth, IHubRegistry {
    using MathLib for uint256;

    /// @dev PricingLib conversions assume decimals <= 18; mirrors the spoke-side bound in Spoke.registerAsset.
    uint8 internal constant MAX_DECIMALS = 18;

    // Assets
    mapping(AssetId => AssetInfo) public asset;

    // Pools
    mapping(PoolId => bytes) public metadata;
    mapping(PoolId => AssetId) public currency;
    mapping(PoolId => mapping(address => bool)) public manager;

    // Policy & authorization ledger
    mapping(PoolId => PolicyInfo) internal _policy;
    mapping(bytes32 authId => uint48 validAfter) public authorizedAfter;

    // Dependencies
    mapping(PoolId => IBridgingHook) public bridgingHook;
    mapping(PoolId => mapping(uint16 centrifugeId => IHubRequestManager)) public hubRequestManager;

    constructor(address deployer) Auth(deployer) {}

    //----------------------------------------------------------------------------------------------
    // Registration methods
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IHubRegistry
    function registerAsset(AssetId assetId, uint8 decimals_) external auth {
        require(!assetId.isNull(), EmptyAssetId());
        require(decimals_ <= MAX_DECIMALS, TooManyDecimals());

        AssetInfo memory current = asset[assetId];
        require(!current.registered || current.decimals == 0 || current.decimals == decimals_, CannotChangeDecimals());

        asset[assetId] = AssetInfo(true, decimals_);

        emit NewAsset(assetId, decimals_);
    }

    /// @inheritdoc IHubRegistry
    function registerPool(PoolId poolId_, address manager_, AssetId currency_) external auth {
        require(!poolId_.isNull(), InvalidPool());
        require(manager_ != address(0), EmptyAccount());
        require(!currency_.isNull(), EmptyCurrency());
        require(isRegistered(currency_), AssetNotFound());
        require(currency[poolId_].isNull(), PoolAlreadyRegistered());

        manager[poolId_][manager_] = true;
        currency[poolId_] = currency_;

        emit NewPool(poolId_, manager_, currency_);
    }

    //----------------------------------------------------------------------------------------------
    // Update methods
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IHubRegistry
    function updateManager(PoolId poolId_, address who, bool canManage) external auth {
        require(exists(poolId_), NonExistingPool());
        require(who != address(0), EmptyAccount());

        manager[poolId_][who] = canManage;

        emit UpdateManager(poolId_, who, canManage);
    }

    /// @inheritdoc IHubRegistry
    function setMetadata(PoolId poolId_, bytes calldata metadata_) external auth {
        require(exists(poolId_), NonExistingPool());

        metadata[poolId_] = metadata_;

        emit SetMetadata(poolId_, metadata_);
    }

    /// @inheritdoc IHubRegistry
    function updateCurrency(PoolId poolId_, AssetId currency_) external auth {
        require(exists(poolId_), NonExistingPool());
        require(!currency_.isNull(), EmptyCurrency());
        require(isRegistered(currency_), AssetNotFound());
        require(asset[currency_].decimals == asset[currency[poolId_]].decimals, CurrencyDecimalsMismatch());

        currency[poolId_] = currency_;

        emit UpdateCurrency(poolId_, currency_);
    }

    /// @inheritdoc IHubRegistry
    function setPolicy(PoolId poolId_, IHubPolicy policy_) external auth {
        require(exists(poolId_), NonExistingPool());

        _policy[poolId_] = PolicyInfo(policy_, _policy[poolId_].nonce + 1);

        emit SetPolicy(poolId_, policy_);
    }

    /// @inheritdoc IHubRegistry
    function setHubRequestManager(PoolId poolId_, uint16 centrifugeId, IHubRequestManager manager_) external auth {
        require(exists(poolId_), NonExistingPool());

        hubRequestManager[poolId_][centrifugeId] = manager_;

        emit SetHubRequestManager(poolId_, centrifugeId, manager_);
    }

    /// @inheritdoc IHubRegistry
    function setBridgingHook(PoolId poolId_, IBridgingHook hook_) external auth {
        require(exists(poolId_), NonExistingPool());

        bridgingHook[poolId_] = hook_;
        emit SetBridgingHook(poolId_, address(hook_));
    }

    //----------------------------------------------------------------------------------------------
    // Authorization ledger
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IHubRegistry
    function initiateAuthorization(PoolId poolId_, address caller, bytes calldata data) external auth {
        PolicyInfo memory info = _policy[poolId_];
        require(address(info.policy) != address(0), PolicyNotInstalled());

        // Only an out-of-policy call may be authorized: an in-policy call would mature instantly.
        uint48 delaySeconds = info.policy.authorizationDelay(poolId_, caller, data);
        require(delaySeconds != 0, InPolicy());

        // Reject re-authorizing: it would silently reset the maturity clock, so cancel first.
        bytes32 id = _authId(poolId_, address(info.policy), info.nonce, data);
        require(authorizedAfter[id] == 0, AlreadyAuthorized());

        uint48 validAfter = uint48(block.timestamp) + delaySeconds;
        authorizedAfter[id] = validAfter;
        emit AuthorizationScheduled(poolId_, caller, id, validAfter, data);
    }

    /// @inheritdoc IHubRegistry
    function cancelAuthorization(PoolId poolId_, address caller, bytes calldata data) external auth {
        bytes32 id = authId(poolId_, data);
        // Revert on a no-op cancel rather than writing a misleading audit entry.
        require(authorizedAfter[id] != 0, Unauthorized());
        delete authorizedAfter[id];
        emit AuthorizationCanceled(poolId_, caller, id);
    }

    /// @inheritdoc IHubRegistry
    function consumeAuthorization(PoolId poolId_, address caller, bytes calldata data, uint48 expiry) external {
        PolicyInfo memory info = _policy[poolId_];
        require(msg.sender == address(info.policy), CallerNotPolicy());

        bytes32 id = _authId(poolId_, address(info.policy), info.nonce, data);
        uint48 validAfter = authorizedAfter[id];
        // Matured and not yet expired: a stale auth fails closed, so it can't be fired much later (once
        // the baseline has drifted) with no fresh veto window.
        require(
            validAfter != 0 && block.timestamp >= validAfter && block.timestamp <= uint256(validAfter) + expiry,
            Unauthorized()
        );
        delete authorizedAfter[id];
        emit AuthorizationConsumed(poolId_, caller, id);
    }

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

    /// @inheritdoc IHubRegistry
    /// @dev `authId` is namespaced by the pool's current policy and its install nonce, so any
    ///      policy change makes every pending authorization unreachable without needing to enumerate
    ///      and clear them — including re-installing a previously used policy address, which must not
    ///      resurrect authorizations matured under its earlier tenure.
    function authId(PoolId poolId_, bytes calldata data) public view returns (bytes32) {
        PolicyInfo memory info = _policy[poolId_];
        return _authId(poolId_, address(info.policy), info.nonce, data);
    }

    /// @dev Computes the id from an already-loaded policy slot, so callers holding it avoid re-reading it.
    function _authId(PoolId poolId_, address policy_, uint64 nonce_, bytes calldata data)
        internal
        pure
        returns (bytes32)
    {
        return keccak256(abi.encodePacked(poolId_.raw(), policy_, nonce_, data));
    }

    /// @inheritdoc IHubRegistry
    function policy(PoolId poolId_) external view returns (IHubPolicy) {
        return _policy[poolId_].policy;
    }

    /// @inheritdoc IHubRegistry
    function policyNonce(PoolId poolId_) external view returns (uint64) {
        return _policy[poolId_].nonce;
    }

    /// @inheritdoc IHubRegistry
    function poolId(uint16 centrifugeId, uint48 postfix) public pure returns (PoolId poolId_) {
        poolId_ = newPoolId(centrifugeId, postfix);
    }

    /// @inheritdoc IHubRegistry
    function decimals(AssetId assetId) public view returns (uint8 decimals_) {
        AssetInfo memory info = asset[assetId];
        require(info.registered, AssetNotFound());
        decimals_ = info.decimals;
    }

    /// @inheritdoc IHubRegistry
    function decimals(PoolId poolId_) public view returns (uint8 decimals_) {
        AssetInfo memory info = asset[currency[poolId_]];
        require(info.registered, AssetNotFound());
        decimals_ = info.decimals;
    }

    /// @inheritdoc IERC6909Decimals
    function decimals(uint256 asset_) external view returns (uint8 decimals_) {
        AssetInfo memory info = asset[AssetId.wrap(asset_.toUint128())];
        require(info.registered, AssetNotFound());
        decimals_ = info.decimals;
    }

    /// @inheritdoc IHubRegistry
    function exists(PoolId poolId_) public view returns (bool) {
        return !currency[poolId_].isNull();
    }

    /// @inheritdoc IHubRegistry
    function isRegistered(AssetId assetId) public view returns (bool) {
        return asset[assetId].registered;
    }
}

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

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

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

src/core/hub/interfaces/IBridgingHook.sol

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

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

struct BridgeSharesParams {
    uint16 originCentrifugeId;
    uint16 targetCentrifugeId;
    PoolId poolId;
    ShareClassId scId;
    bytes32 sender;
    bytes32 receiver;
    uint128 amount;
    uint128 extraGasLimit;
    address refund;
}

/// @dev Fields the hook is allowed to modify. Immutable routing fields (poolId, scId, chain IDs,
///      sender) are intentionally absent.
struct BridgeSharesResult {
    bytes32 receiver;
    uint128 amount;
    uint128 extraGasLimit;
    address refund;
}

interface IBridgingHook {
    /// @notice Called before forwarding a cross-chain share transfer.
    function onBridgeShares(BridgeSharesParams calldata p) external returns (BridgeSharesResult memory);
}

src/core/hub/interfaces/IHubRegistry.sol

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

import {IBridgingHook} from "./IBridgingHook.sol";
import {IHubRequestManager} from "./IHubRequestManager.sol";

import {IERC6909Decimals} from "../../../misc/interfaces/IERC6909.sol";

import {PoolId} from "../../types/PoolId.sol";
import {AssetId} from "../../types/AssetId.sol";
import {IHubPolicy} from "../../utils/interfaces/IPolicy.sol";

interface IHubRegistry is IERC6909Decimals {
    //----------------------------------------------------------------------------------------------
    // Structs
    //----------------------------------------------------------------------------------------------

    /// @notice Registration state and decimals of a registered asset.
    struct AssetInfo {
        bool registered;
        uint8 decimals;
    }

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

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

    event NewAsset(AssetId indexed assetId, uint8 decimals);
    event NewPool(PoolId indexed poolId, address indexed manager, AssetId indexed currency);
    event UpdateManager(PoolId indexed poolId, address indexed manager, bool canManage);
    event SetMetadata(PoolId indexed poolId, bytes metadata);
    event UpdateCurrency(PoolId indexed poolId, AssetId currency);
    event SetHubRequestManager(PoolId indexed poolId, uint16 indexed centrifugeId, IHubRequestManager manager);
    event SetBridgingHook(PoolId indexed poolId, address hook);
    event SetPolicy(PoolId indexed poolId, IHubPolicy policy);

    /// @notice Emitted when an out-of-policy Hub call is authorized: this starts the policy timelock.
    ///         The authorization matures at `validAfter` and may then run, unless cancelled first. `data`
    ///         is the exact authorized calldata, included so the action is decodable straight from logs.
    event AuthorizationScheduled(
        PoolId indexed poolId, address indexed caller, bytes32 indexed authId, uint48 validAfter, bytes data
    );
    /// @notice Emitted when a pending authorization is cancelled (a manager, or a sentinel via its
    ///         Supervisor). `caller` is whoever cancelled it.
    event AuthorizationCanceled(PoolId indexed poolId, address indexed caller, bytes32 indexed authId);
    /// @notice Emitted when a matured authorization is consumed by an executing out-of-policy call.
    ///         `caller` is the manager whose Hub call consumed it.
    event AuthorizationConsumed(PoolId indexed poolId, address indexed caller, bytes32 indexed authId);

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

    error NonExistingPool();
    error InvalidPool();
    /// @notice Dispatched when {registerAsset} would move an asset's decimals off a nonzero value. Only
    ///         an unset entry (0) may be replaced; anything else may be re-registered at the value it
    ///         already holds, and at nothing else.
    error CannotChangeDecimals();
    error PoolAlreadyRegistered();
    error EmptyAccount();
    error EmptyCurrency();
    error EmptyShareClassManager();
    error AssetNotFound();
    /// @notice Dispatched when {registerAsset} targets the null AssetId, which is the "no currency"
    ///         sentinel: registering it would make decimal lookups succeed for non-existent pools.
    error EmptyAssetId();
    /// @notice Dispatched when {registerAsset} declares more than 18 decimals, the bound PricingLib
    ///         conversions assume (mirrors the spoke-side check in Spoke.registerAsset).
    error TooManyDecimals();
    /// @notice Dispatched when {updateCurrency} targets a currency whose decimals differ from the pool's current
    ///         currency; pool decimals must stay fixed to match already-deployed share tokens.
    error CurrencyDecimalsMismatch();
    /// @notice Dispatched when {initiateAuthorization} targets a pool with no policy installed (nothing to classify).
    error PolicyNotInstalled();
    /// @notice Dispatched when {initiateAuthorization} targets a call that is currently in policy (nothing to authorize).
    error InPolicy();
    /// @notice Dispatched when {initiateAuthorization} targets a call that already has an authorization (cancel first).
    error AlreadyAuthorized();
    /// @notice Dispatched when {consumeAuthorization} finds no matured, unexpired authorization, or when
    ///         {cancelAuthorization} finds no authorization to cancel.
    error Unauthorized();
    /// @notice Dispatched when {consumeAuthorization} is called by anyone other than the pool's policy.
    error CallerNotPolicy();

    //----------------------------------------------------------------------------------------------
    // Registration methods
    //----------------------------------------------------------------------------------------------

    /// @notice Register an asset, or re-register one whose decimals are unset or unchanged
    /// @dev Re-registering is how a value the spoke read off a token that had not been initialized yet is
    ///      corrected: a stored 0 may be replaced. Anything else may only be re-registered at the value it
    ///      already holds, which keeps repeated registration idempotent without letting a decimals change
    ///      reach an asset that live pools price against. {NewAsset} is emitted every time, not only the
    ///      first, so consumers must treat it as an upsert.
    /// @dev The bound is the point rather than caution. RegisterAsset routes over the global adapter set,
    ///      so it reaches pools running adapters of their own; a forged one must not be able to retune the
    ///      decimals that claim payouts convert through.
    /// @dev Not covered: a token reporting a wrong nonzero `decimals()` before initialization rather than
    ///      0, whose entry is then final. Both reported cases report 0.
    /// @dev A parked RegisterAsset carrying a value since superseded — a `0` read before the token was
    ///      initialized, retried after a later registration wrote the real decimals — now reverts rather
    ///      than applying. That is the intent: a stale message must not walk the entry backwards. It stays
    ///      in `failedMessages` and is inert there, RegisterAsset being nonce-free.
    /// @param assetId The asset identifier; must not be the null AssetId
    /// @param decimals_ The number of decimals for the asset, at most 18
    function registerAsset(AssetId assetId, uint8 decimals_) external;

    /// @notice Register a new pool
    /// @param poolId The pool identifier
    /// @param manager The initial manager address for the pool
    /// @param currency The currency asset for the pool; must already be registered
    function registerPool(PoolId poolId, address manager, AssetId currency) external;

    //----------------------------------------------------------------------------------------------
    // Update methods
    //----------------------------------------------------------------------------------------------

    /// @notice Allow/disallow an address as a manager for the pool
    /// @param poolId The pool identifier
    /// @param who The address to update manager status for
    /// @param canManage Whether the address can manage the pool
    function updateManager(PoolId poolId, address who, bool canManage) external;

    /// @notice Set the hub request manager for a pool on a specific network
    /// @param poolId The pool identifier
    /// @param centrifuge The network identifier
    /// @param manager The hub request manager contract
    function setHubRequestManager(PoolId poolId, uint16 centrifuge, IHubRequestManager manager) external;

    /// @notice Sets metadata for this pool
    /// @param poolId The pool identifier
    /// @param metadata The metadata to attach
    function setMetadata(PoolId poolId, bytes calldata metadata) external;

    /// @notice Updates a dependency of the system
    /// @param poolId The pool identifier
    /// @param what The dependency identifier
    /// @param dependency The dependency contract address

    /// @notice Updates the currency of the pool
    /// @param poolId The pool identifier
    /// @param currency The new currency asset
    function updateCurrency(PoolId poolId, AssetId currency) external;

    /// @notice Install or replace the policy for a pool
    /// @dev    Auth-gated: written through by the Hub, which enforces the policy on the change itself
    /// @param poolId The pool identifier
    /// @param policy The policy contract (address(0) to clear)
    function setPolicy(PoolId poolId, IHubPolicy policy) external;

    //----------------------------------------------------------------------------------------------
    // Authorization ledger
    //----------------------------------------------------------------------------------------------

    /// @notice Pre-authorize a future, out-of-policy Hub call. Callable only by the Hub (the manager check
    ///         lives in {IHub.initiateAuthorization}). The pool's policy classifies the call, using `caller` as the
    ///         authorizing manager; an in-policy call can't be authorized. Matures after the classified
    ///         delay, after which a guarded Hub call whose calldata byte-matches `data` consumes it.
    /// @param poolId The pool the call targets
    /// @param caller The manager authorizing the call (for classification and the audit event)
    /// @param data The exact future Hub calldata being authorized
    function initiateAuthorization(PoolId poolId, address caller, bytes calldata data) external;

    /// @notice Cancel a pending authorization. Callable only by the Hub (the manager check lives in
    ///         {IHub.cancelAuthorization}; sentinels act through their Supervisor, itself a registered
    ///         Hub manager).
    /// @param poolId The pool the authorization targets
    /// @param caller The manager cancelling the authorization (for the audit event)
    /// @param data The exact Hub calldata that was authorized
    function cancelAuthorization(PoolId poolId, address caller, bytes calldata data) external;

    /// @notice Consume a matured authorization for an executing out-of-policy call. Callable only by the
    ///         pool's installed policy (from its {IPolicy.enforce}). Reverts unless an authorization
    ///         exists, has matured, and is still within `expiry` of maturing.
    /// @param poolId The pool the call targets
    /// @param caller The manager whose Hub call is executing (for the audit event)
    /// @param data The exact Hub calldata being executed
    /// @param expiry The window, after maturing, in which the authorization stays executable
    function consumeAuthorization(PoolId poolId, address caller, bytes calldata data, uint48 expiry) external;

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

    /// @notice The timestamp at which a pending authorization matures (0 if none).
    /// @param authId The authorization identifier, see {authId}
    function authorizedAfter(bytes32 authId) external view returns (uint48 validAfter);

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

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

    /// @notice Returns the metadata attached to the pool, if any
    /// @param poolId The pool identifier
    /// @return The metadata bytes
    function metadata(PoolId poolId) external view returns (bytes memory);

    /// @notice Returns the currency of the pool
    /// @param poolId The pool identifier
    /// @return The currency asset identifier
    function currency(PoolId poolId) external view returns (AssetId);

    /// @notice Returns whether the account is a manager
    /// @param poolId The pool identifier
    /// @param who The address to check
    /// @return Whether the address is a manager
    function manager(PoolId poolId, address who) external view returns (bool);

    /// @notice Returns the hub request manager for a pool and centrifuge ID
    /// @param poolId The pool identifier
    /// @param centrifugeId The network identifier
    /// @return The hub request manager contract
    function hubRequestManager(PoolId poolId, uint16 centrifugeId) external view returns (IHubRequestManager);

    /// @notice Returns the policy installed for a pool (address(0) if none)
    /// @param poolId The pool identifier
    /// @return The policy contract
    function policy(PoolId poolId) external view returns (IHubPolicy);

    /// @notice Compute a pool ID given an ID postfix
    /// @param centrifugeId The network identifier
    /// @param postfix The pool ID postfix
    /// @return poolId The computed pool identifier
    function poolId(uint16 centrifugeId, uint48 postfix) external view returns (PoolId poolId);

    /// @notice Returns the decimals for an asset
    /// @param assetId The asset identifier
    /// @return The number of decimals
    function decimals(AssetId assetId) external view returns (uint8);

    /// @notice Returns the decimals for a pool
    /// @param poolId The pool identifier
    /// @return The number of decimals
    function decimals(PoolId poolId) external view returns (uint8);

    /// @notice Checks the existence of a pool
    /// @param poolId The pool identifier
    /// @return Whether the pool exists
    function exists(PoolId poolId) external view returns (bool);

    /// @notice Checks the existence of an asset
    /// @param assetId The asset identifier
    /// @return Whether the asset is registered
    function isRegistered(AssetId assetId) external view returns (bool);

    /// @notice Returns the registration state and decimals of an asset
    /// @param assetId The asset identifier
    /// @return registered Whether the asset is registered
    /// @return decimals The number of decimals
    function asset(AssetId assetId) external view returns (bool registered, uint8 decimals);

    /// @notice Set or clear the bridging hook for a pool
    /// @param poolId The pool identifier
    /// @param hook The hook contract, or address(0) to clear
    function setBridgingHook(PoolId poolId, IBridgingHook hook) external;

    /// @notice Returns the bridging hook for a pool, or address(0) if none
    function bridgingHook(PoolId poolId) external view returns (IBridgingHook);
}

src/core/hub/interfaces/IHubRequestManager.sol

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

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

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

interface IHubRequestManager is IERC165 {
    /// @notice Handles a request originating from the Hub side, similar to HubHelpers.request
    function request(PoolId poolId, ShareClassId scId, AssetId assetId, bytes calldata payload) external;
}

interface IHubRequestManagerNotifications is IERC165 {
    /// @notice Notify a deposit for the given request located in the chain where the asset belongs
    function notifyDeposit(
        PoolId poolId,
        ShareClassId scId,
        AssetId depositAssetId,
        RequestId requestId,
        uint32 maxClaims,
        address refund
    ) external payable;

    /// @notice Notify a redemption for the given request located in the chain where the asset belongs
    function notifyRedeem(
        PoolId poolId,
        ShareClassId scId,
        AssetId payoutAssetId,
        RequestId requestId,
        uint32 maxClaims,
        address refund
    ) external payable;
}

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

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

/// @dev Opaque identifier for a request within a (poolId, scId, assetId) tuple. Numeric so implementations can
///      pack structured ids (e.g. vault address and an incremental local id) and expose the ERC-7540/ERC-8161
///      `uint256 requestId` surface without conversion.
type RequestId is uint256;

function raw(RequestId requestId) pure returns (uint256) {
    return RequestId.unwrap(requestId);
}

using {raw} for RequestId 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/Auth.sol

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

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

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

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

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

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

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

src/misc/interfaces/IAuth.sol

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

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

    error NotAuthorized();

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

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

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

src/misc/interfaces/IERC165.sol

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

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

src/misc/interfaces/IERC6909.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

    error EmptyURI();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

src/misc/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;
    }
}
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.