Skip to content
Verified contractPartialAGPL-3.0-or-later

RIVRMessageDispatcher

Address0x3f0f6587e1494f47044bdca16992ecd3fc239146
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.34

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 200 runs
License
AGPL-3.0-or-later
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,354,933
Creation transaction
0xa93929e51d…5d33ee7318

contracts/core/messaging/RIVRMessageDispatcher.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

import {IGateway} from "./interfaces/IGateway.sol";
import {IMultiAdapter} from "./interfaces/IMultiAdapter.sol";
import {IScheduleAuth} from "./interfaces/IScheduleAuth.sol";
import {ITokenRecoverer} from "./interfaces/ITokenRecoverer.sol";
import {IMessageDispatcher} from "./interfaces/IMessageDispatcher.sol";
import {MessageLib, VaultUpdateKind} from "./libraries/MessageLib.sol";
import {ISpokeMessageSender, IHubMessageSender, IScheduleAuthMessageSender} from "./interfaces/IGatewaySenders.sol";
import {
    ISpokeGatewayHandler,
    IBalanceSheetGatewayHandler,
    IHubGatewayHandler,
    IContractUpdateGatewayHandler,
    IVaultRegistryGatewayHandler
} from "./interfaces/IGatewayHandlers.sol";

import {Auth} from "../../misc/Auth.sol";
import {D18} from "../../misc/types/D18.sol";
import {CastLib} from "../../misc/libraries/CastLib.sol";
import {MathLib} from "../../misc/libraries/MathLib.sol";
import {BytesLib} from "../../misc/libraries/BytesLib.sol";
import {IRecoverable} from "../../misc/interfaces/IRecoverable.sol";

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

/// @title  RIVRMessageDispatcher
/// @notice This contract serializes and dispatches outgoing cross-chain messages, handling both local and
///         remote destinations by either directly invoking local handlers or routing through the gateway.
contract RIVRMessageDispatcher is Auth, IMessageDispatcher {
    using CastLib for *;
    using MessageLib for *;
    using BytesLib for bytes;
    using MathLib for uint256;

    PoolId internal constant GLOBAL_POOL = PoolId.wrap(0);
    uint16 public immutable localRIVRId;

    IGateway public gateway;
    IMultiAdapter public multiAdapter;
    ISpokeGatewayHandler public spoke;
    IScheduleAuth public immutable scheduleAuth;
    IHubGatewayHandler public hubHandler;
    ITokenRecoverer public tokenRecoverer;
    IBalanceSheetGatewayHandler public balanceSheet;
    IVaultRegistryGatewayHandler public vaultRegistry;
    IContractUpdateGatewayHandler public contractUpdater;

    constructor(uint16 localRIVRId_, IScheduleAuth scheduleAuth_, IGateway gateway_, address deployer)
        Auth(deployer)
    {
        localRIVRId = localRIVRId_;
        scheduleAuth = scheduleAuth_;
        gateway = gateway_;
    }

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

    /// @inheritdoc IMessageDispatcher
    function file(bytes32 what, address data) external auth {
        if (what == "hubHandler") hubHandler = IHubGatewayHandler(data);
        else if (what == "spoke") spoke = ISpokeGatewayHandler(data);
        else if (what == "gateway") gateway = IGateway(data);
        else if (what == "balanceSheet") balanceSheet = IBalanceSheetGatewayHandler(data);
        else if (what == "vaultRegistry") vaultRegistry = IVaultRegistryGatewayHandler(data);
        else if (what == "contractUpdater") contractUpdater = IContractUpdateGatewayHandler(data);
        else if (what == "tokenRecoverer") tokenRecoverer = ITokenRecoverer(data);
        else revert FileUnrecognizedParam();

        emit File(what, data);
    }

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

    /// @inheritdoc IHubMessageSender
    function sendNotifyPool(uint16 rivrId, PoolId poolId, address refund) external payable auth {
        if (rivrId == localRIVRId) {
            spoke.addPool(poolId);
            _refund(refund);
        } else {
            _send(rivrId, MessageLib.NotifyPool({poolId: poolId.raw()}).serialize(), false, refund);
        }
    }

    /// @inheritdoc IHubMessageSender
    function sendNotifyShareClass(
        uint16 rivrId,
        PoolId poolId,
        ShareClassId scId,
        string memory name,
        string memory symbol,
        uint8 decimals,
        bytes32 salt,
        bytes32 hook,
        address refund
    ) external payable auth {
        if (rivrId == localRIVRId) {
            spoke.addShareClass(poolId, scId, name, symbol, decimals, salt, hook.toAddress());
            _refund(refund);
        } else {
            _send(
                rivrId,
                MessageLib.NotifyShareClass({
                        poolId: poolId.raw(),
                        scId: scId.raw(),
                        name: name,
                        symbol: symbol.toBytes32(),
                        decimals: decimals,
                        salt: salt,
                        hook: hook
                    }).serialize(),
                false,
                refund
            );
        }
    }

    /// @inheritdoc IHubMessageSender
    function sendNotifyShareMetadata(
        uint16 rivrId,
        PoolId poolId,
        ShareClassId scId,
        string memory name,
        string memory symbol,
        address refund
    ) external payable auth {
        if (rivrId == localRIVRId) {
            spoke.updateShareMetadata(poolId, scId, name, symbol);
            _refund(refund);
        } else {
            _send(
                rivrId,
                MessageLib.NotifyShareMetadata({
                        poolId: poolId.raw(), scId: scId.raw(), name: name, symbol: symbol.toBytes32()
                    }).serialize(),
                false,
                refund
            );
        }
    }

    /// @inheritdoc IHubMessageSender
    function sendUpdateShareHook(uint16 rivrId, PoolId poolId, ShareClassId scId, bytes32 hook, address refund)
        external
        payable
        auth
    {
        if (rivrId == localRIVRId) {
            spoke.updateShareHook(poolId, scId, hook.toAddress());
            _refund(refund);
        } else {
            _send(
                rivrId,
                MessageLib.UpdateShareHook({poolId: poolId.raw(), scId: scId.raw(), hook: hook}).serialize(),
                false,
                refund
            );
        }
    }

    /// @inheritdoc IHubMessageSender
    function sendNotifyPricePoolPerShare(
        uint16 chainId,
        PoolId poolId,
        ShareClassId scId,
        D18 pricePoolPerShare,
        uint64 computedAt,
        address refund
    ) external payable auth {
        if (chainId == localRIVRId) {
            spoke.updatePricePoolPerShare(poolId, scId, pricePoolPerShare, computedAt);
            _refund(refund);
        } else {
            _send(
                chainId,
                MessageLib.NotifyPricePoolPerShare({
                        poolId: poolId.raw(), scId: scId.raw(), price: pricePoolPerShare.raw(), timestamp: computedAt
                    }).serialize(),
                false,
                refund
            );
        }
    }

    /// @inheritdoc IHubMessageSender
    function sendNotifyPricePoolPerAsset(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        D18 pricePoolPerAsset,
        address refund
    ) external payable auth {
        uint64 timestamp = block.timestamp.toUint64();
        if (assetId.rivrId() == localRIVRId) {
            spoke.updatePricePoolPerAsset(poolId, scId, assetId, pricePoolPerAsset, timestamp);
            _refund(refund);
        } else {
            _send(
                assetId.rivrId(),
                MessageLib.NotifyPricePoolPerAsset({
                        poolId: poolId.raw(),
                        scId: scId.raw(),
                        assetId: assetId.raw(),
                        price: pricePoolPerAsset.raw(),
                        timestamp: timestamp
                    }).serialize(),
                false,
                refund
            );
        }
    }

    /// @inheritdoc IHubMessageSender
    function sendUpdateRestriction(
        uint16 rivrId,
        PoolId poolId,
        ShareClassId scId,
        bytes calldata payload,
        uint128 extraGasLimit,
        address refund
    ) external payable auth {
        if (rivrId == localRIVRId) {
            spoke.updateRestriction(poolId, scId, payload);
            _refund(refund);
        } else {
            _send(
                rivrId,
                MessageLib.UpdateRestriction({
                        poolId: poolId.raw(), scId: scId.raw(), extraGasLimit: extraGasLimit, payload: payload
                    }).serialize(),
                false,
                refund
            );
        }
    }

    /// @inheritdoc IHubMessageSender
    function sendTrustedContractUpdate(
        uint16 rivrId,
        PoolId poolId,
        ShareClassId scId,
        bytes32 target,
        bytes calldata payload,
        uint128 extraGasLimit,
        address refund
    ) external payable auth {
        if (rivrId == localRIVRId) {
            contractUpdater.trustedCall(poolId, scId, target.toAddress(), payload);
            _refund(refund);
        } else {
            _send(
                rivrId,
                MessageLib.TrustedContractUpdate({
                        poolId: poolId.raw(),
                        scId: scId.raw(),
                        target: target,
                        extraGasLimit: extraGasLimit,
                        payload: payload
                    }).serialize(),
                false,
                refund
            );
        }
    }

    /// @inheritdoc IHubMessageSender
    function sendUpdateVault(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        bytes32 vaultOrFactory,
        VaultUpdateKind kind,
        uint128 extraGasLimit,
        address refund
    ) external payable auth {
        if (assetId.rivrId() == localRIVRId) {
            vaultRegistry.updateVault(poolId, scId, assetId, vaultOrFactory.toAddress(), kind);
            _refund(refund);
        } else {
            _send(
                assetId.rivrId(),
                MessageLib.UpdateVault({
                        poolId: poolId.raw(),
                        scId: scId.raw(),
                        assetId: assetId.raw(),
                        vaultOrFactory: vaultOrFactory,
                        kind: uint8(kind),
                        extraGasLimit: extraGasLimit
                    }).serialize(),
                false,
                refund
            );
        }
    }

    /// @inheritdoc IHubMessageSender
    function sendSetRequestManager(uint16 rivrId, PoolId poolId, bytes32 manager, address refund)
        external
        payable
        auth
    {
        if (rivrId == localRIVRId) {
            spoke.setRequestManager(poolId, IRequestManager(manager.toAddress()));
            _refund(refund);
        } else {
            _send(
                rivrId,
                MessageLib.SetRequestManager({poolId: poolId.raw(), manager: manager}).serialize(),
                false,
                refund
            );
        }
    }

    /// @inheritdoc IHubMessageSender
    function sendUpdateBalanceSheetManager(
        uint16 rivrId,
        PoolId poolId,
        bytes32 who,
        bool canManage,
        address refund
    ) external payable auth {
        if (rivrId == localRIVRId) {
            balanceSheet.updateManager(poolId, who.toAddress(), canManage);
            _refund(refund);
        } else {
            _send(
                rivrId,
                MessageLib.UpdateBalanceSheetManager({poolId: poolId.raw(), who: who, canManage: canManage})
                    .serialize(),
                false,
                refund
            );
        }
    }

    /// @inheritdoc IHubMessageSender
    function sendSetMaxAssetPriceAge(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        uint64 maxPriceAge,
        address refund
    ) external payable auth {
        if (assetId.rivrId() == localRIVRId) {
            spoke.setMaxAssetPriceAge(poolId, scId, assetId, maxPriceAge);
            _refund(refund);
        } else {
            _send(
                assetId.rivrId(),
                MessageLib.SetMaxAssetPriceAge({
                        poolId: poolId.raw(), scId: scId.raw(), assetId: assetId.raw(), maxPriceAge: maxPriceAge
                    }).serialize(),
                false,
                refund
            );
        }
    }

    /// @inheritdoc IHubMessageSender
    function sendSetMaxSharePriceAge(
        uint16 rivrId,
        PoolId poolId,
        ShareClassId scId,
        uint64 maxPriceAge,
        address refund
    ) external payable auth {
        if (rivrId == localRIVRId) {
            spoke.setMaxSharePriceAge(poolId, scId, maxPriceAge);
            _refund(refund);
        } else {
            _send(
                rivrId,
                MessageLib.SetMaxSharePriceAge({poolId: poolId.raw(), scId: scId.raw(), maxPriceAge: maxPriceAge})
                    .serialize(),
                false,
                refund
            );
        }
    }

    /// @inheritdoc IScheduleAuthMessageSender
    function sendScheduleUpgrade(uint16 rivrId, bytes32 target, address refund) external payable auth {
        if (rivrId == localRIVRId) {
            scheduleAuth.scheduleRely(target.toAddress());
            _refund(refund);
        } else {
            _send(rivrId, MessageLib.ScheduleUpgrade({target: target}).serialize(), false, refund);
        }
    }

    /// @inheritdoc IScheduleAuthMessageSender
    function sendCancelUpgrade(uint16 rivrId, bytes32 target, address refund) external payable auth {
        if (rivrId == localRIVRId) {
            scheduleAuth.cancelRely(target.toAddress());
            _refund(refund);
        } else {
            _send(rivrId, MessageLib.CancelUpgrade({target: target}).serialize(), false, refund);
        }
    }

    /// @inheritdoc IScheduleAuthMessageSender
    function sendRecoverTokens(
        uint16 rivrId,
        bytes32 target,
        bytes32 token,
        uint256 tokenId,
        bytes32 to,
        uint256 amount,
        address refund
    ) external payable auth {
        if (rivrId == localRIVRId) {
            tokenRecoverer.recoverTokens(
                IRecoverable(target.toAddress()), token.toAddress(), tokenId, to.toAddress(), amount
            );
            _refund(refund);
        } else {
            _send(
                rivrId,
                MessageLib.RecoverTokens({target: target, token: token, tokenId: tokenId, to: to, amount: amount})
                    .serialize(),
                false,
                refund
            );
        }
    }

    /// @inheritdoc ISpokeMessageSender
    function sendInitiateTransferShares(
        uint16 targetRIVRId,
        PoolId poolId,
        ShareClassId scId,
        bytes32 receiver,
        uint128 amount,
        uint128 extraGasLimit,
        uint128 remoteExtraGasLimit,
        address refund
    ) external payable auth {
        if (poolId.rivrId() == localRIVRId) {
            hubHandler.initiateTransferShares{value: msg.value}(
                localRIVRId, targetRIVRId, poolId, scId, receiver, amount, remoteExtraGasLimit, refund
            );
        } else {
            _send(
                poolId.rivrId(),
                MessageLib.InitiateTransferShares({
                        rivrId: targetRIVRId,
                        poolId: poolId.raw(),
                        scId: scId.raw(),
                        receiver: receiver,
                        amount: amount,
                        remoteExtraGasLimit: remoteExtraGasLimit,
                        extraGasLimit: extraGasLimit
                    }).serialize(),
                false,
                refund
            );
        }
    }

    /// @inheritdoc IHubMessageSender
    function sendExecuteTransferShares(
        uint16 originRIVRId,
        uint16 targetRIVRId,
        PoolId poolId,
        ShareClassId scId,
        bytes32 receiver,
        uint128 amount,
        uint128 extraGasLimit,
        address refund
    ) external payable auth {
        if (targetRIVRId == localRIVRId) {
            // Spoke chain X => Hub chain Y => Spoke chain Y
            spoke.executeTransferShares(poolId, scId, receiver, amount);
            _refund(refund);
        } else {
            _send(
                targetRIVRId,
                MessageLib.ExecuteTransferShares({
                        poolId: poolId.raw(),
                        scId: scId.raw(),
                        receiver: receiver,
                        amount: amount,
                        extraGasLimit: extraGasLimit
                    }).serialize(),
                originRIVRId != localRIVRId,
                refund
            );
        }
    }

    /// @inheritdoc ISpokeMessageSender
    function sendUpdateHoldingAmount(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        UpdateData calldata data,
        D18 pricePoolPerAsset,
        uint128 extraGasLimit,
        address refund
    ) external payable auth {
        if (poolId.rivrId() == localRIVRId) {
            hubHandler.updateHoldingAmount(
                localRIVRId,
                poolId,
                scId,
                assetId,
                data.netAmount,
                pricePoolPerAsset,
                data.isIncrease,
                data.isSnapshot,
                data.nonce
            );
            _refund(refund);
        } else {
            _send(
                poolId.rivrId(),
                MessageLib.UpdateHoldingAmount({
                        poolId: poolId.raw(),
                        scId: scId.raw(),
                        assetId: assetId.raw(),
                        amount: data.netAmount,
                        pricePoolPerAsset: pricePoolPerAsset.raw(),
                        timestamp: uint64(block.timestamp),
                        isIncrease: data.isIncrease,
                        isSnapshot: data.isSnapshot,
                        nonce: data.nonce,
                        extraGasLimit: extraGasLimit
                    }).serialize(),
                false,
                refund
            );
        }
    }

    /// @inheritdoc ISpokeMessageSender
    function sendUpdateShares(
        PoolId poolId,
        ShareClassId scId,
        UpdateData calldata data,
        uint128 extraGasLimit,
        address refund
    ) external payable auth {
        if (poolId.rivrId() == localRIVRId) {
            hubHandler.updateShares(
                localRIVRId, poolId, scId, data.netAmount, data.isIncrease, data.isSnapshot, data.nonce
            );
            _refund(refund);
        } else {
            _send(
                poolId.rivrId(),
                MessageLib.UpdateShares({
                        poolId: poolId.raw(),
                        scId: scId.raw(),
                        shares: data.netAmount,
                        timestamp: uint64(block.timestamp),
                        isIssuance: data.isIncrease,
                        isSnapshot: data.isSnapshot,
                        nonce: data.nonce,
                        extraGasLimit: extraGasLimit
                    }).serialize(),
                false,
                refund
            );
        }
    }

    /// @inheritdoc ISpokeMessageSender
    function sendRegisterAsset(uint16 rivrId, AssetId assetId, uint8 decimals, address refund)
        external
        payable
        auth
    {
        if (rivrId == localRIVRId) {
            hubHandler.registerAsset(assetId, decimals);
            _refund(refund);
        } else {
            _send(
                rivrId,
                MessageLib.RegisterAsset({assetId: assetId.raw(), decimals: decimals}).serialize(),
                false,
                refund
            );
        }
    }

    /// @inheritdoc ISpokeMessageSender
    function sendRequest(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        bytes calldata payload,
        uint128 extraGasLimit,
        bool unpaidMode,
        address refund
    ) external payable auth {
        if (poolId.rivrId() == localRIVRId) {
            hubHandler.request(poolId, scId, assetId, payload);
            _refund(refund);
        } else {
            _send(
                poolId.rivrId(),
                MessageLib.Request({
                        poolId: poolId.raw(),
                        scId: scId.raw(),
                        assetId: assetId.raw(),
                        extraGasLimit: extraGasLimit,
                        payload: payload
                    }).serialize(),
                unpaidMode,
                refund
            );
        }
    }

    /// @inheritdoc ISpokeMessageSender
    function sendUntrustedContractUpdate(
        PoolId poolId,
        ShareClassId scId,
        bytes32 target,
        bytes calldata payload,
        bytes32 sender,
        uint128 extraGasLimit,
        address refund
    ) external payable auth {
        uint16 hubRIVRId = poolId.rivrId();

        if (hubRIVRId == localRIVRId) {
            contractUpdater.untrustedCall(poolId, scId, target.toAddress(), payload, localRIVRId, sender);
            _refund(refund);
        } else {
            _send(
                hubRIVRId,
                MessageLib.UntrustedContractUpdate({
                        poolId: poolId.raw(),
                        scId: scId.raw(),
                        target: target,
                        sender: sender,
                        extraGasLimit: extraGasLimit,
                        payload: payload
                    }).serialize(),
                false,
                refund
            );
        }
    }

    /// @inheritdoc IHubMessageSender
    function sendRequestCallback(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        bytes calldata payload,
        uint128 extraGasLimit,
        bool unpaidMode,
        address refund
    ) external payable auth {
        if (assetId.rivrId() == localRIVRId) {
            spoke.requestCallback(poolId, scId, assetId, payload);
            _refund(refund);
        } else {
            _send(
                assetId.rivrId(),
                MessageLib.RequestCallback({
                        poolId: poolId.raw(),
                        scId: scId.raw(),
                        assetId: assetId.raw(),
                        extraGasLimit: extraGasLimit,
                        payload: payload
                    }).serialize(),
                unpaidMode,
                refund
            );
        }
    }

    /// @inheritdoc IHubMessageSender
    function sendSetPoolAdapters(
        uint16 rivrId,
        PoolId poolId,
        bytes32[] memory adapters,
        uint8 threshold,
        uint8 recoveryIndex,
        address refund
    ) external payable auth {
        if (rivrId == localRIVRId) {
            revert CannotBeSentLocally();
        } else {
            _send(
                rivrId,
                MessageLib.SetPoolAdapters({
                        poolId: poolId.raw(), threshold: threshold, recoveryIndex: recoveryIndex, adapterList: adapters
                    }).serialize(),
                false,
                refund
            );
        }
    }

    function sendUpdateGatewayManager(uint16 rivrId, PoolId poolId, bytes32 who, bool canManage, address refund)
        external
        payable
        auth
    {
        if (rivrId == localRIVRId) {
            gateway.updateManager(poolId, who.toAddress(), canManage);
            _refund(refund);
        } else {
            _send(
                rivrId,
                MessageLib.UpdateGatewayManager({poolId: poolId.raw(), who: who, canManage: canManage}).serialize(),
                false,
                refund
            );
        }
    }

    function _send(uint16 rivrId, bytes memory message, bool unpaidMode, address refund) internal {
        gateway.send{value: msg.value}(rivrId, message, unpaidMode, refund);
    }

    function _refund(address refund) internal {
        if (msg.value > 0) {
            (bool success,) = payable(refund).call{value: msg.value}("");
            require(success, CannotRefund());
        }
    }
}

contracts/core/interfaces/IRequestManager.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

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

interface IRequestManager {
    //----------------------------------------------------------------------------------------------
    // Errors
    //----------------------------------------------------------------------------------------------

    error UnknownRequestCallbackType();

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

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

contracts/core/messaging/interfaces/IAdapter.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

interface IAdapter {
    //----------------------------------------------------------------------------------------------
    // Errors
    //----------------------------------------------------------------------------------------------

    error NotEntrypoint();
    error UnknownChainId();

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

    /// @notice Send a payload to the destination chain
    /// @param rivrId 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 rivrId, bytes calldata payload, uint256 gasLimit, address refund)
        external
        payable
        returns (bytes32 adapterData);

    /// @notice Estimate the total cost in native gas tokens
    /// @param rivrId 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 rivrId, bytes calldata payload, uint256 gasLimit) external view returns (uint256);
}

contracts/core/messaging/interfaces/IGateway.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

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 rivrId, PoolId poolId, bool isBlocked);
    event PrepareMessage(uint16 indexed rivrId, PoolId poolId, bytes message);
    event UnderpaidBatch(uint16 indexed rivrId, bytes batch, bytes32 batchHash);
    event RepayBatch(uint16 indexed rivrId, bytes batch);
    event ExecuteMessage(uint16 indexed rivrId, bytes32 messageHash);
    event FailMessage(uint16 indexed rivrId, 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 rivrId RIVR ID associated to this block
    /// @param poolId PoolId associated to this block
    /// @param canSend If can send messages or not
    function blockOutgoing(uint16 rivrId, PoolId poolId, bool canSend) external;

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

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

    /// @notice Retry a failed message
    /// @param rivrId The destination chain
    /// @param message The message to retry
    function retry(uint16 rivrId, bytes memory message) external;

    /// @notice Handling outgoing messages
    /// @param rivrId 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 rivrId, 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);
}

contracts/core/messaging/interfaces/IGatewayHandlers.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

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

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

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

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

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

    /// @notice Update a holding by request from Vaults.
    function updateHoldingAmount(
        uint16 rivrId,
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        uint128 amount,
        D18 pricePoolPerAsset,
        bool isIncrease,
        bool isSnapshot,
        uint64 nonce
    ) external;

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

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

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

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

    /// @notice     New share class details from an existing RIVR pool are added.
    function addShareClass(
        PoolId poolId,
        ShareClassId scId,
        string memory tokenName,
        string memory tokenSymbol,
        uint8 decimals,
        bytes32 salt,
        address hook
    ) external;

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

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

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

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

    /// @notice Updates the hook of a share class token
    /// @param  poolId The rivr pool id
    /// @param  scId The share class id
    /// @param  hook The new hook address
    function updateShareHook(PoolId poolId, ShareClassId scId, address hook) external;

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

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

    /// @notice Updates the max price age of an asset
    /// @param  poolId The rivr pool id
    /// @param  scId The share class id
    /// @param  assetId The asset id
    /// @param  maxPriceAge new max price age value
    function setMaxAssetPriceAge(PoolId poolId, ShareClassId scId, AssetId assetId, uint64 maxPriceAge) external;

    /// @notice Updates the max price age of a share
    /// @param  poolId The rivr pool id
    /// @param  scId The share class id
    /// @param  maxPriceAge new max price age value
    function setMaxSharePriceAge(PoolId poolId, ShareClassId scId, uint64 maxPriceAge) external;

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

/// @notice Interface for the update contract method, called by message
interface IContractUpdateGatewayHandler {
    /// @notice Updates the target address. Generic update function from Hub to Spoke
    /// @param  poolId The rivr pool id
    /// @param  scId The share class id
    /// @param  target The target address to be called
    /// @param  update The payload to be processed by the target address
    function trustedCall(PoolId poolId, ShareClassId scId, address target, bytes memory update) external;

    /// @notice Updates the target address. Generic update function from Spoke to Hub
    /// @param  poolId The rivr pool id
    /// @param  scId The share class id
    /// @param  target The target address to be called
    /// @param  update The payload to be processed by the target address
    function untrustedCall(
        PoolId poolId,
        ShareClassId scId,
        address target,
        bytes memory update,
        uint16 rivrId,
        bytes32 sender
    ) external;
}

/// @notice Interface for methods implemented by a balance sheet
interface IBalanceSheetGatewayHandler {
    function updateManager(PoolId poolId, address who, bool canManage) external;
}

/// @notice Interface for VaultRegistry methods called by messages
interface IVaultRegistryGatewayHandler {
    /// @notice Updates a vault based on VaultUpdateKind
    /// @param  poolId The rivr pool id
    /// @param  scId The share class id
    /// @param  assetId The asset id
    /// @param  vaultOrFactory The address of the vault or the factory, depending on the kind value
    /// @param  kind The kind of action applied
    function updateVault(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        address vaultOrFactory,
        VaultUpdateKind kind
    ) external;
}

contracts/core/messaging/interfaces/IGatewaySenders.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

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

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

interface ILocalRIVRId {
    error CannotBeSentLocally();

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

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

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

    /// @notice Creates and send the message
    function sendRecoverTokens(
        uint16 rivrId,
        bytes32 target,
        bytes32 token,
        uint256 tokenId,
        bytes32 to,
        uint256 amount,
        address refund
    ) external payable;
}

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

    /// @notice Creates and send the message
    function sendNotifyShareClass(
        uint16 rivrId,
        PoolId poolId,
        ShareClassId scId,
        string memory name,
        string memory symbol,
        uint8 decimals,
        bytes32 salt,
        bytes32 hook,
        address refund
    ) external payable;

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

    /// @notice Creates and send the message
    function sendUpdateShareHook(uint16 rivrId, PoolId poolId, ShareClassId scId, bytes32 hook, address refund)
        external
        payable;

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

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

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

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

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

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

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

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

    /// @notice Creates and send the message
    function sendSetMaxAssetPriceAge(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        uint64 maxPriceAge,
        address refund
    ) external payable;

    /// @notice Creates and send the message
    function sendSetMaxSharePriceAge(
        uint16 rivrId,
        PoolId poolId,
        ShareClassId scId,
        uint64 maxPriceAge,
        address refund
    ) external payable;

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

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

    /// @notice Creates and send the message
    function sendUpdateGatewayManager(uint16 rivrId, PoolId poolId, bytes32 who, bool canManage, address refund)
        external
        payable;
}

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

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

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

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

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

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

    /// @notice Creates and sends an UntrustedContractUpdate message
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param target The hub-side target contract (as bytes32)
    /// @param sender The spoke-side initiator (as bytes32)
    /// @param payload The update payload
    /// @param extraGasLimit Additional gas for cross-chain execution
    /// @param refund Address to refund excess payment
    function sendUntrustedContractUpdate(
        PoolId poolId,
        ShareClassId scId,
        bytes32 target,
        bytes calldata payload,
        bytes32 sender,
        uint128 extraGasLimit,
        address refund
    ) external payable;
}

contracts/core/messaging/interfaces/IMessageDispatcher.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

import {ISpokeMessageSender, IHubMessageSender, IScheduleAuthMessageSender} from "./IGatewaySenders.sol";

interface IMessageDispatcher is IScheduleAuthMessageSender, ISpokeMessageSender, IHubMessageSender {
    /// @notice Emitted when a call to `file()` was performed.
    event File(bytes32 indexed what, address addr);

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

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

    /// @notice Updates a contract parameter.
    /// @param what Name of the parameter to update.
    ///         Accepts a `bytes32` representation of 'hubRegistry' string value.
    /// @param data New value given to the `what` parameter
    function file(bytes32 what, address data) external;
}

contracts/core/messaging/interfaces/IMessageHandler.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

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

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

contracts/core/messaging/interfaces/IMultiAdapter.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

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

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

uint8 constant MAX_ADAPTER_COUNT = 8;

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

    /// @dev Each adapter struct is packed with the quorum, threshold and recoveryIndex to reduce SLOADs on handle
    struct Adapter {
        /// @notice Starts at 1 and maps to id - 1 as the index on the adapters array
        uint8 id;
        /// @notice Number of configured adapters
        uint8 quorum;
        /// @notice Number of votes required for a message to be executed. Less-equal to quorum
        uint8 threshold;
        /// @notice Index in the adapter array to start consider the adapter as recovery adapter
        uint8 recoveryIndex;
        /// @notice Each time the quorum is decreased, a new session starts which invalidates old votes
        uint128 activeSessionId;
    }

    struct Inbound {
        /// @dev Counts are stored as integers (instead of boolean values) to accommodate duplicate
        ///      messages (e.g. two investments from the same user with the same amount) being
        ///      processed in parallel. The entire struct is packed in a single bytes32 slot.
        ///      Max int16 = 32,767 so at most 32,767 duplicate messages can be processed in parallel
        int16[MAX_ADAPTER_COUNT] votes;
        /// @notice Each time adapters are updated, a new session starts which invalidates old votes
        uint128 sessionId;
    }

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

    event File(bytes32 indexed what, address addr);
    event SetAdapters(uint16 rivrId, PoolId poolId, IAdapter[] adapters, uint8 threshold, uint8 recoveryIndex);
    event HandlePayload(uint16 indexed rivrId, bytes32 indexed payloadId, bytes payload, IAdapter adapter);
    event SendPayload(
        uint16 indexed rivrId,
        bytes32 indexed payloadId,
        bytes payload,
        IAdapter adapter,
        bytes32 adapterData,
        uint256 gasLimit,
        uint256 gasPaid,
        address refund
    );

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

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

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

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

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

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

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

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

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

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

    /// @notice Configure new adapters for a determined pool.
    ///         Messages sent but not yet received when this is executed will be lost.
    /// @param  rivrId Chain where the adapters are associated to.
    /// @param  poolId PoolId associated to the adapters
    /// @param  adapters New adapter addresses already deployed.
    ///         If the array is empty, it disables the usage for messages of that pool.
    /// @param  threshold Minimum number of adapters required to process the messages
    ///         If not wanted a threshold set `adapters.length` value
    /// @param  recoveryIndex Index in adapters array from where consider the adapter as recovery adapter.
    ///         If not wanted a recoveryIndex set `adapters.length` value
    ///
    ///         A recovery adapter is an adapter that does not decrease their votes below 0.
    ///         it is, it can never have a debt on messages not received.
    ///         It can be used to easily emulate receiving a missing message by some of the others adapters.
    ///
    ///         i.e: Suppose a configuration of `[Adapter1, Adapter2, RecoveryAdapter]` with threshold 2.
    ///         Both `Adapter1` and `Adapter2` will need always need to handle the message, each one, to process it.
    ///         In case some of those fail, the losing vote can be recover through the `RecoveryAdapter`` to reach
    ///         threshold 2.
    function setAdapters(
        uint16 rivrId,
        PoolId poolId,
        IAdapter[] calldata adapters,
        uint8 threshold,
        uint8 recoveryIndex
    ) external;

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

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

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

    /// @notice Index in the adapter array to start consider the adapter as recovery adapter
    /// @param rivrId Chain where the adapter is configured for
    /// @param poolId PoolId associated to the adapters
    /// @return Recovery index
    function recoveryIndex(uint16 rivrId, PoolId poolId) external view returns (uint8);

    /// @notice Gets the current active routers session id
    /// @dev When the adapters are updated with new ones, each new set of adapters has their own sessionId
    /// @param rivrId Chain where the adapters are configured for
    /// @param poolId PoolId associated to the adapters
    /// @return The active session id
    function activeSessionId(uint16 rivrId, PoolId poolId) external view returns (uint128);

    /// @notice Counts how many times each incoming messages has been received per adapter.
    /// @dev    It supports parallel messages ( duplicates ). That means that the incoming messages could be
    ///         the result of two or more independent request from the user of the same type.
    ///         i.e. Same user would like to deposit same underlying asset with the same amount more then once.
    /// @param  rivrId Chain where the adapter is configured for
    /// @param  payloadHash The hash value of the incoming message.
    /// @return The votes array
    function votes(uint16 rivrId, bytes32 payloadHash) external view returns (int16[MAX_ADAPTER_COUNT] memory);

    /// @notice Returns the address of the adapter at the given id
    /// @param rivrId Chain where the adapters are configured for
    /// @param poolId PoolId associated to the adapters
    /// @param id The adapter id
    /// @return The adapter at the specified id
    function adapters(uint16 rivrId, PoolId poolId, uint256 id) external view returns (IAdapter);
}

contracts/core/messaging/interfaces/IScheduleAuth.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

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

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

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

contracts/core/messaging/interfaces/ITokenRecoverer.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

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

interface ITokenRecoverer {
    event RecoverTokens(
        IRecoverable indexed target, address indexed token, uint256 tokenId, address indexed to, uint256 amount
    );

    /// @notice Recovers tokens from a target contract
    /// @param target The contract to recover tokens from
    /// @param token The token address to recover
    /// @param tokenId The token ID (0 for ERC20, non-zero for ERC6909)
    /// @param to The address to send recovered tokens to
    /// @param amount The amount of tokens to recover
    function recoverTokens(IRecoverable target, address token, uint256 tokenId, address to, uint256 amount) external;
}

contracts/core/messaging/libraries/MessageLib.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

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 rivrId;
        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),
            rivrId: 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.rivrId,
            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);
    }
}

contracts/core/types/AssetId.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

/// @dev Composite Id of the rivrId (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 rivrId(AssetId assetId) pure returns (uint16) {
    return uint16(AssetId.unwrap(assetId) >> 112);
}

function newAssetId(uint16 rivrId_, uint64 counter) pure returns (AssetId) {
    return AssetId.wrap((uint128(rivrId_) << 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, rivrId, eq as ==} for AssetId global;

contracts/core/types/PoolId.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

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

using MathLib for uint256;

type PoolId is uint64;

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

function newPoolId(uint16 rivrId_, uint48 localPoolId) pure returns (PoolId) {
    return PoolId.wrap((uint64(rivrId_) << 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 {rivrId, isNull, raw, isEqual as ==} for PoolId global;

contracts/core/types/ShareClassId.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

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;

contracts/misc/Auth.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

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

contracts/misc/interfaces/IAuth.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

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

contracts/misc/interfaces/IRecoverable.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

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

contracts/misc/libraries/BytesLib.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

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

contracts/misc/libraries/CastLib.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

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

contracts/misc/libraries/MathLib.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

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

contracts/misc/types/D18.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.34;

// Small library to handle fixed point number operations with 18 decimals with static typing support.

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

type D18 is uint128;

error D18_DivisionByZero();

using MathLib for uint256;

/// @dev add two D18 types
function add(D18 d1, D18 d2) pure returns (D18) {
    return D18.wrap(D18.unwrap(d1) + D18.unwrap(d2));
}

/// @dev subtract two D18 types
function sub(D18 d1, D18 d2) pure returns (D18) {
    return D18.wrap(D18.unwrap(d1) - D18.unwrap(d2));
}

/// @dev Divides one D18 by another one while retaining precision:
/// - nominator (decimal): 50e18
/// - denominator (decimal):  2e19
/// - result (decimal): 25e17
function divD18(D18 d1, D18 d2) pure returns (D18) {
    return D18.wrap(MathLib.mulDiv(D18.unwrap(d1), 1e18, D18.unwrap(d2)).toUint128());
}

/// @dev Multiplies one D18 with another one while retaining precision:
/// - value1 (decimal): 50e18
/// - value2 (decimal):  2e19
/// - result (decimal): 100e19
function mulD18(D18 d1, D18 d2) pure returns (D18) {
    return D18.wrap(MathLib.mulDiv(D18.unwrap(d1), D18.unwrap(d2), 1e18).toUint128());
}

/// @dev Returns the reciprocal of a D18 decimal, i.e. 1 / d.
///      Example: if d = 2.0 (2e18 internally), reciprocal(d) = 0.5 (5e17 internally).
function reciprocal(D18 d) pure returns (D18) {
    uint128 val = D18.unwrap(d);
    require(val != 0, D18_DivisionByZero());
    return d18(1e18, val);
}

/// @dev Multiplies a decimal by an integer. i.e:
/// - d (decimal):      1_500_000_000_000_000_000
/// - value (integer):  4_000_000_000_000_000_000
/// - result (integer): 6_000_000_000_000_000_000
function mulUint128(D18 d, uint128 value, MathLib.Rounding rounding) pure returns (uint128) {
    return MathLib.mulDiv(D18.unwrap(d), value, 1e18, rounding).toUint128();
}

/// @dev Multiplies a decimal by an integer. i.e:
/// - d (decimal):      1_500_000_000_000_000_000
/// - value (integer):  4_000_000_000_000_000_000
/// - result (integer): 6_000_000_000_000_000_000
function mulUint256(D18 d, uint256 value, MathLib.Rounding rounding) pure returns (uint256) {
    return MathLib.mulDiv(D18.unwrap(d), value, 1e18, rounding);
}

/// @dev  Divides an integer by a decimal, i.e.
/// @dev  Same as mulDiv for integers, i.e:
/// - d (decimal):      2_000_000_000_000_000_000
/// - value (integer):  100_000_000_000_000_000_000
/// - result (integer): 50_000_000_000_000_000_000
function reciprocalMulUint128(D18 d, uint128 value, MathLib.Rounding rounding) pure returns (uint128) {
    return MathLib.mulDiv(value, 1e18, d.raw(), rounding).toUint128();
}

/// @dev  Divides an integer by a decimal, i.e.
/// @dev  Same as mulDiv for integers, i.e:
/// - d (decimal):      2_000_000_000_000_000_000
/// - value (integer):  100_000_000_000_000_000_000
/// - result (integer): 50_000_000_000_000_000_000
function reciprocalMulUint256(D18 d, uint256 value, MathLib.Rounding rounding) pure returns (uint256) {
    return MathLib.mulDiv(value, 1e18, d.raw(), rounding);
}

/// @dev Easy way to construct a decimal number
function d18(uint128 value) pure returns (D18) {
    return D18.wrap(value);
}

/// @dev Easy way to construct a decimal number
function d18(uint128 num, uint128 den) pure returns (D18) {
    return D18.wrap(MathLib.mulDiv(num, 1e18, den).toUint128());
}

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

function isZero(D18 a) pure returns (bool) {
    return D18.unwrap(a) == 0;
}

function isNotZero(D18 a) pure returns (bool) {
    return D18.unwrap(a) != 0;
}

function raw(D18 d) pure returns (uint128) {
    return D18.unwrap(d);
}

using {
    add as +,
    sub as -,
    divD18 as /,
    eq,
    mulD18 as *,
    mulUint128,
    mulUint256,
    reciprocalMulUint128,
    reciprocalMulUint256,
    reciprocal,
    raw,
    isZero,
    isNotZero
} for D18 global;
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.