Skip to content
Verified contractPartialBUSL-1.1

GasService

Address0xbebef21d686a957dececce6a58455fa0f16754be
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
24,319,314
Creation transaction
0xc63334e8e1…17c170ed3e

src/core/messaging/GasService.sol

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

import {IGasService} from "./interfaces/IGasService.sol";
import {PROCESS_FAIL_MESSAGE_GAS} from "./interfaces/IGateway.sol";
import {IMessageProperties} from "./interfaces/IMessageProperties.sol";
import {MessageLib, MessageType, VaultUpdateKind} from "./libraries/MessageLib.sol";

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

/// @title  GasService
/// @notice This contract stores the gas limits (in gas units) for cross-chain message execution.
///         These values are used by adapters to determine how much gas to allocate for
///         message execution on destination chains.
contract GasService is IGasService {
    using MessageLib for *;

    /// @dev Takes into account Gateway + MultiAdapter computation
    uint128 public constant BASE_COST = 75_000;

    /// @dev Adds an extra cost to recover token admin message to ensure different assets can transfer successfully
    uint128 public constant RECOVERY_TOKEN_EXTRA_COST = 100_000;

    uint128 public constant DEFAULT_SUPPORTED_TX_LIMIT = 10; // In millions of gas units

    /// @dev An encoded array of the block limits of the first 32 centrifugeId.
    ///      Measured in millions of gas units
    uint256 public immutable txLimitsPerCentrifugeId;

    uint128 public immutable scheduleUpgrade;
    uint128 public immutable cancelUpgrade;
    uint128 public immutable recoverTokens;
    uint128 public immutable registerAsset;
    uint128 public immutable setPoolAdapters;
    uint128 public immutable request;
    uint128 public immutable notifyPool;
    uint128 public immutable notifyShareClass;
    uint128 public immutable notifyPricePoolPerShare;
    uint128 public immutable notifyPricePoolPerAsset;
    uint128 public immutable notifyShareMetadata;
    uint128 public immutable updateShareHook;
    uint128 public immutable initiateTransferShares;
    uint128 public immutable executeTransferShares;
    uint128 public immutable updateRestriction;
    uint128 public immutable trustedContractUpdate;
    uint128 public immutable requestCallback;
    uint128 public immutable updateVaultDeployAndLink;
    uint128 public immutable updateVaultLink;
    uint128 public immutable updateVaultUnlink;
    uint128 public immutable setRequestManager;
    uint128 public immutable updateBalanceSheetManager;
    uint128 public immutable updateHoldingAmount;
    uint128 public immutable updateShares;
    uint128 public immutable maxAssetPriceAge;
    uint128 public immutable maxSharePriceAge;
    uint128 public immutable updateGatewayManager;
    uint128 public immutable untrustedContractUpdate;

    constructor(uint8[32] memory txLimits) {
        for (uint256 i; i < txLimits.length; i++) {
            uint256 value = txLimits[i] > 0 ? txLimits[i] : DEFAULT_SUPPORTED_TX_LIMIT;
            txLimitsPerCentrifugeId += value << (31 - i) * 8;
        }

        // NOTE: Below values should be updated using script/utils/benchmark.sh
        scheduleUpgrade = _gasValue(118954);
        cancelUpgrade = _gasValue(99410);
        recoverTokens = RECOVERY_TOKEN_EXTRA_COST + _gasValue(175073);
        registerAsset = _gasValue(129155);
        setPoolAdapters = _gasValue(509965); // using MAX_ADAPTER_COUNT
        request = _gasValue(244858);
        notifyPool = _gasValue(1305733); // create escrow case
        notifyShareClass = _gasValue(1883390);
        notifyPricePoolPerShare = _gasValue(127234);
        notifyPricePoolPerAsset = _gasValue(131047);
        notifyShareMetadata = _gasValue(140797);
        updateShareHook = _gasValue(116761);
        initiateTransferShares = _gasValue(307060);
        executeTransferShares = _gasValue(197870);
        updateRestriction = _gasValue(137670);
        trustedContractUpdate = _gasValue(168921);
        requestCallback = _gasValue(355279); // approve deposit case
        updateVaultDeployAndLink = _gasValue(2866252);
        updateVaultLink = _gasValue(207895);
        updateVaultUnlink = _gasValue(156662);
        setRequestManager = _gasValue(126098);
        updateBalanceSheetManager = _gasValue(124987);
        updateHoldingAmount = _gasValue(325854);
        updateShares = _gasValue(223271);
        maxAssetPriceAge = _gasValue(131132);
        maxSharePriceAge = _gasValue(128066);
        updateGatewayManager = _gasValue(122645);
        untrustedContractUpdate = _gasValue(110086);
    }

    /// @inheritdoc IMessageProperties
    function messageOverallGasLimit(uint16 centrifugeId, bytes calldata message) public view returns (uint128) {
        uint128 value = messageProcessingGasLimit(centrifugeId, message) + BASE_COST;
        // Multiply by 64/63 is because EIP-150 pass 63/64 gas to each method call
        // Calls from adapters requires adding more jumps (3): Executor -> Adapter -> MultiAdapter -> Gateway.
        return value * 262144 / 250047; // Equivalent to: value * 64 * 64 * 64 / (63 * 63 * 63)
    }

    /// @inheritdoc IMessageProperties
    /// @dev This method does not require any 64/63 because it's called from the same point is benchmarked
    function messageProcessingGasLimit(uint16 centrifugeId, bytes calldata message) public view returns (uint128) {
        return _messageBaseGasLimit(centrifugeId, message) + message.messageExtraGasLimit();
    }

    function _messageBaseGasLimit(uint16, bytes calldata message) internal view returns (uint128) {
        MessageType kind = message.messageType();

        if (kind == MessageType.ScheduleUpgrade) return scheduleUpgrade;
        if (kind == MessageType.CancelUpgrade) return cancelUpgrade;
        if (kind == MessageType.RecoverTokens) return recoverTokens;
        if (kind == MessageType.RegisterAsset) return registerAsset;
        if (kind == MessageType.SetPoolAdapters) return setPoolAdapters;
        if (kind == MessageType.Request) return request;
        if (kind == MessageType.NotifyPool) return notifyPool;
        if (kind == MessageType.NotifyShareClass) return notifyShareClass;
        if (kind == MessageType.NotifyPricePoolPerShare) return notifyPricePoolPerShare;
        if (kind == MessageType.NotifyPricePoolPerAsset) return notifyPricePoolPerAsset;
        if (kind == MessageType.NotifyShareMetadata) return notifyShareMetadata;
        if (kind == MessageType.UpdateShareHook) return updateShareHook;
        if (kind == MessageType.InitiateTransferShares) return initiateTransferShares;
        if (kind == MessageType.ExecuteTransferShares) return executeTransferShares;
        if (kind == MessageType.UpdateRestriction) return updateRestriction;
        if (kind == MessageType.TrustedContractUpdate) return trustedContractUpdate;
        if (kind == MessageType.RequestCallback) return requestCallback;
        if (kind == MessageType.UpdateVault) {
            VaultUpdateKind vaultKind = VaultUpdateKind(message.deserializeUpdateVault().kind);
            if (vaultKind == VaultUpdateKind.DeployAndLink) return updateVaultDeployAndLink;
            if (vaultKind == VaultUpdateKind.Link) return updateVaultLink;
            if (vaultKind == VaultUpdateKind.Unlink) return updateVaultUnlink;
            return 100_000; // Some high value just to compute the call and fail inside the Gateway try/catch
        }
        if (kind == MessageType.SetRequestManager) return setRequestManager;
        if (kind == MessageType.UpdateBalanceSheetManager) return updateBalanceSheetManager;
        if (kind == MessageType.UpdateHoldingAmount) return updateHoldingAmount;
        if (kind == MessageType.UpdateShares) return updateShares;
        if (kind == MessageType.SetMaxAssetPriceAge) return maxAssetPriceAge;
        if (kind == MessageType.SetMaxSharePriceAge) return maxSharePriceAge;
        if (kind == MessageType.UpdateGatewayManager) return updateGatewayManager;
        if (kind == MessageType.UntrustedContractUpdate) return untrustedContractUpdate;
        revert InvalidMessageType(); // Unreachable
    }

    /// @inheritdoc IMessageProperties
    function maxBatchGasLimit(uint16 centrifugeId) external view returns (uint128) {
        // txLimitsPerCentrifugeId counts millions of gas units, then we need to multiply by 1_000_000
        return (centrifugeId < 32 ? uint8(bytes32(txLimitsPerCentrifugeId)[centrifugeId]) : DEFAULT_SUPPORTED_TX_LIMIT)
            * 1_000_000;
    }

    /// @inheritdoc IMessageProperties
    function messageLength(bytes calldata message) external pure returns (uint16) {
        return message.messageLength();
    }

    /// @inheritdoc IMessageProperties
    function messagePoolId(bytes calldata message) external pure returns (PoolId) {
        return message.messagePoolId();
    }

    /// @dev - BASE_COST adds some offset to the benchmarked message
    ///      - PROCESS_FAIL_MESSAGE_GAS is an extra required to process a possible message failure
    ///        so we add here the adapter call required gas.
    function _gasValue(uint128 value) internal pure returns (uint128) {
        // NOTE: The benchmarked value passed as param is measured from the call to the MessageProcessor.
        // It means, it already contains the Gateway -> MessageProcessor jump EIP-150 multiplier
        return uint128(PROCESS_FAIL_MESSAGE_GAS) + value;
    }
}

src/core/messaging/interfaces/IAdapter.sol

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

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

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

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

/// @dev Max cost. No messages will take more that this
uint128 constant MAX_MESSAGE_COST = 3_200_000;

/// @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 IMessageProperties {
    error InvalidMessageType();

    function scheduleUpgrade() external view returns (uint128);
    function cancelUpgrade() external view returns (uint128);
    function recoverTokens() 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 updateShareHook() external view returns (uint128);
    function initiateTransferShares() external view returns (uint128);
    function executeTransferShares() external view returns (uint128);
    function updateRestriction() external view returns (uint128);
    function trustedContractUpdate() 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 updateBalanceSheetManager() external view returns (uint128);
    function updateHoldingAmount() external view returns (uint128);
    function updateShares() external view returns (uint128);
    function maxAssetPriceAge() external view returns (uint128);
    function maxSharePriceAge() external view returns (uint128);
    function updateGatewayManager() external view returns (uint128);
    function untrustedContractUpdate() external view returns (uint128);
}

src/core/messaging/interfaces/IGateway.sol

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

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

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

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

// Reserved gas amount for processing a message failure (assuming the worst case)
uint256 constant PROCESS_FAIL_MESSAGE_GAS = 35_000;

// 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 UpdateManager(PoolId poolId, address who, bool canManage);
    event BlockOutgoing(uint16 centrifugeId, PoolId poolId, bool isBlocked);
    event PrepareMessage(uint16 indexed centrifugeId, PoolId 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 SetRefundAddress(PoolId poolId, IRecoverable refund);
    event DepositSubsidy(PoolId indexed poolId, address indexed sender, uint256 amount);
    event WithdrawSubsidy(PoolId indexed poolId, address indexed sender, uint256 amount);

    //----------------------------------------------------------------------------------------------
    // 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 is sent but the gateway is blocked for sending messages
    error OutgoingBlocked();

    /// @notice Dispatched when an account is not valid to withdraw subsidized pool funds
    error CannotRefund();

    /// @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 Configures a manager address for a pool
    /// @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;

    /// @notice Indicates if the gateway for a determined pool can send messages or not
    /// @param centrifugeId Centrifuge ID associated to this block
    /// @param poolId PoolId associated to this block
    /// @param canSend If can send messages or not
    function blockOutgoing(uint16 centrifugeId, PoolId poolId, bool canSend) 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
    /// @param centrifugeId The destination chain
    /// @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 Returns the current gateway batching level
    /// @return Whether the gateway is currently batching
    function isBatching() external view returns (bool);
}

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

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

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

/// @notice Defines methods to get properties from raw messages
interface IMessageProperties {
    /// @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 Inspect the message to return the length
    function messageLength(bytes calldata message) external view returns (uint16);

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

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

enum MessageType {
    /// @dev Placeholder for null message type
    _Invalid,
    // -- Pool independent messages
    ScheduleUpgrade,
    CancelUpgrade,
    RecoverTokens,
    RegisterAsset,
    SetPoolAdapters,
    // -- Pool dependent messages
    NotifyPool,
    NotifyShareClass,
    NotifyPricePoolPerShare,
    NotifyPricePoolPerAsset,
    NotifyShareMetadata,
    UpdateShareHook,
    InitiateTransferShares,
    ExecuteTransferShares,
    UpdateRestriction,
    UpdateVault,
    UpdateBalanceSheetManager,
    UpdateGatewayManager,
    UpdateHoldingAmount,
    UpdateShares,
    SetMaxAssetPriceAge,
    SetMaxSharePriceAge,
    Request,
    RequestCallback,
    SetRequestManager,
    TrustedContractUpdate,
    UntrustedContractUpdate
}

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

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

    error UnknownMessageType();

    /// @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) +
        (161 << uint8(MessageType.RecoverTokens) * 8) +
        (18  << uint8(MessageType.RegisterAsset) * 8) +
        (13  << 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) +
        (57  << uint8(MessageType.UpdateShareHook) * 8) +
        (107  << uint8(MessageType.InitiateTransferShares) * 8) +
        (89  << uint8(MessageType.ExecuteTransferShares) * 8) +
        (41  << uint8(MessageType.UpdateRestriction) * 8) +
        (90  << uint8(MessageType.UpdateVault) * 8) +
        (42  << uint8(MessageType.UpdateBalanceSheetManager) * 8) +
        (42  << uint8(MessageType.UpdateGatewayManager) * 8) +
        (107  << uint8(MessageType.UpdateHoldingAmount) * 8) +
        (75  << uint8(MessageType.UpdateShares) * 8) +
        (49  << uint8(MessageType.SetMaxAssetPriceAge) * 8) +
        (33  << uint8(MessageType.SetMaxSharePriceAge) * 8) +
        (57  << uint8(MessageType.Request) * 8) +
        (57  << uint8(MessageType.RequestCallback) * 8) +
        (41  << uint8(MessageType.SetRequestManager) * 8) +
        (73  << uint8(MessageType.TrustedContractUpdate) * 8) +
        (105  << uint8(MessageType.UntrustedContractUpdate) * 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(type(MessageType).max), UnknownMessageType());

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

        // Special treatment for messages with dynamic size:
        if (kind == uint8(MessageType.UpdateRestriction)) {
            length += 2 + message.toUint16(length); //payloadLength
        } else if (kind == uint8(MessageType.TrustedContractUpdate)) {
            length += 2 + message.toUint16(length); //payloadLength
        } else if (kind == uint8(MessageType.UntrustedContractUpdate)) {
            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.SetPoolAdapters)) {
            length += message.toUint16(11) * 32; // message with variable length
        }
    }

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

        // All messages from NotifyPool to the end contains a PoolId in position 1.
        if (kind >= uint8(MessageType.NotifyPool)) {
            return PoolId.wrap(message.toUint64(1));
        }

        return PoolId.wrap(0);
    }

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

        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.TrustedContractUpdate)) {
            return message.toUint128(57);
        } else if (kind == uint8(MessageType.UntrustedContractUpdate)) {
            return message.toUint128(89);
        } 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.UpdateHoldingAmount)) {
            return message.toUint128(91);
        } 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);
    }

    //---------------------------------------
    //    RecoverTokens
    //---------------------------------------

    struct RecoverTokens {
        bytes32 target;
        bytes32 token;
        uint256 tokenId;
        bytes32 to;
        uint256 amount;
    }

    function deserializeRecoverTokens(bytes memory data) internal pure returns (RecoverTokens memory) {
        require(messageType(data) == MessageType.RecoverTokens, UnknownMessageType());
        return RecoverTokens({
            target: data.toBytes32(1),
            token: data.toBytes32(33),
            tokenId: data.toUint256(65),
            to: data.toBytes32(97),
            amount: data.toUint256(129)
        });
    }

    function serialize(RecoverTokens memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(MessageType.RecoverTokens, t.target, t.token, t.tokenId, t.to, t.amount);
    }

    //---------------------------------------
    //    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;
        uint8 recoveryIndex;
        bytes32[] adapterList;
    }

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

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

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

    function serialize(SetPoolAdapters memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(
            MessageType.SetPoolAdapters,
            t.poolId,
            t.threshold,
            t.recoveryIndex,
            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 hook;
    }

    function deserializeNotifyShareClass(bytes memory data) internal pure returns (NotifyShareClass memory) {
        require(messageType(data) == MessageType.NotifyShareClass, UnknownMessageType());
        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),
            hook: data.toBytes32(218)
        });
    }

    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.hook
        );
    }

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

    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)
        });
    }

    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
        );
    }

    //---------------------------------------
    //    UpdateShareHook
    //---------------------------------------

    struct UpdateShareHook {
        uint64 poolId;
        bytes16 scId;
        bytes32 hook;
    }

    function deserializeUpdateShareHook(bytes memory data) internal pure returns (UpdateShareHook memory) {
        require(messageType(data) == MessageType.UpdateShareHook, UnknownMessageType());
        return UpdateShareHook({poolId: data.toUint64(1), scId: data.toBytes16(9), hook: data.toBytes32(25)});
    }

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

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

    struct InitiateTransferShares {
        uint64 poolId;
        bytes16 scId;
        uint16 centrifugeId;
        bytes32 receiver;
        uint128 amount;
        uint128 remoteExtraGasLimit;
        uint128 extraGasLimit;
    }

    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)
        });
    }

    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
        );
    }

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

    //---------------------------------------
    //    TrustedContractUpdate
    //---------------------------------------

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

    function deserializeTrustedContractUpdate(bytes memory data) internal pure returns (TrustedContractUpdate memory) {
        require(messageType(data) == MessageType.TrustedContractUpdate, UnknownMessageType());
        uint16 payloadLength = data.toUint16(73);
        return TrustedContractUpdate({
            poolId: data.toUint64(1),
            scId: data.toBytes16(9),
            target: data.toBytes32(25),
            extraGasLimit: data.toUint128(57),
            payload: data.slice(75, payloadLength)
        });
    }

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

    //---------------------------------------
    //    UntrustedContractUpdate
    //---------------------------------------

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

    function deserializeUntrustedContractUpdate(bytes memory data)
        internal
        pure
        returns (UntrustedContractUpdate memory)
    {
        require(messageType(data) == MessageType.UntrustedContractUpdate, UnknownMessageType());
        uint16 payloadLength = data.toUint16(105);
        return UntrustedContractUpdate({
            poolId: data.toUint64(1),
            scId: data.toBytes16(9),
            target: data.toBytes32(25),
            sender: data.toBytes32(57),
            extraGasLimit: data.toUint128(89),
            payload: data.slice(107, payloadLength)
        });
    }

    function serialize(UntrustedContractUpdate memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(
            MessageType.UntrustedContractUpdate,
            t.poolId,
            t.scId,
            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;
    }

    function deserializeUpdateVault(bytes memory data) internal pure returns (UpdateVault memory) {
        require(messageType(data) == MessageType.UpdateVault, UnknownMessageType());
        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)
        });
    }

    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
        );
    }

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

    //---------------------------------------
    //   UpdateBalanceSheetManager
    //---------------------------------------

    struct UpdateBalanceSheetManager {
        uint64 poolId;
        bytes32 who;
        bool canManage;
    }

    function deserializeUpdateBalanceSheetManager(bytes memory data)
        internal
        pure
        returns (UpdateBalanceSheetManager memory)
    {
        require(messageType(data) == MessageType.UpdateBalanceSheetManager, UnknownMessageType());
        return UpdateBalanceSheetManager({poolId: data.toUint64(1), who: data.toBytes32(9), canManage: data.toBool(41)});
    }

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

    //---------------------------------------
    //    UpdateHoldingAmount
    //---------------------------------------

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

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

        return UpdateHoldingAmount({
            poolId: data.toUint64(1),
            scId: data.toBytes16(9),
            assetId: data.toUint128(25),
            amount: data.toUint128(41),
            pricePoolPerAsset: data.toUint128(57),
            timestamp: data.toUint64(73),
            isIncrease: data.toBool(81),
            isSnapshot: data.toBool(82),
            nonce: data.toUint64(83),
            extraGasLimit: data.toUint128(91)
        });
    }

    function serialize(UpdateHoldingAmount memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(
            MessageType.UpdateHoldingAmount,
            t.poolId,
            t.scId,
            t.assetId,
            t.amount,
            t.pricePoolPerAsset,
            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
        );
    }

    //---------------------------------------
    //   SetMaxAssetPriceAge
    //---------------------------------------

    struct SetMaxAssetPriceAge {
        uint64 poolId;
        bytes16 scId;
        uint128 assetId;
        uint64 maxPriceAge;
    }

    function deserializeSetMaxAssetPriceAge(bytes memory data) internal pure returns (SetMaxAssetPriceAge memory) {
        require(messageType(data) == MessageType.SetMaxAssetPriceAge, UnknownMessageType());
        return SetMaxAssetPriceAge({
            poolId: data.toUint64(1),
            scId: data.toBytes16(9),
            assetId: data.toUint128(25),
            maxPriceAge: data.toUint64(41)
        });
    }

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

    //---------------------------------------
    //   SetMaxSharePriceAge
    //---------------------------------------

    struct SetMaxSharePriceAge {
        uint64 poolId;
        bytes16 scId;
        uint64 maxPriceAge;
    }

    function deserializeSetMaxSharePriceAge(bytes memory data) internal pure returns (SetMaxSharePriceAge memory) {
        require(messageType(data) == MessageType.SetMaxSharePriceAge, UnknownMessageType());
        return SetMaxSharePriceAge({poolId: data.toUint64(1), scId: data.toBytes16(9), maxPriceAge: data.toUint64(25)});
    }

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

    //---------------------------------------
    //   UpdateGatewayManager
    //---------------------------------------

    struct UpdateGatewayManager {
        uint64 poolId;
        bytes32 who;
        bool canManage;
    }

    function deserializeUpdateGatewayManager(bytes memory data) internal pure returns (UpdateGatewayManager memory) {
        require(messageType(data) == MessageType.UpdateGatewayManager, UnknownMessageType());
        return UpdateGatewayManager({poolId: data.toUint64(1), who: data.toBytes32(9), canManage: data.toBool(41)});
    }

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

src/core/types/PoolId.sol

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

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

using MathLib for uint256;

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

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;
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": true
  },
  "optimizer": {
    "runs": 1,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/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/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.