Skip to content
Verified contractPartialAGPL-3.0-or-later

RIVRPoolManager

Address0x032e378db45385b21184ec39ef9ae43a1afb5690
Balance

0 ETH

 

Transactions

9

 

Compiler

solc 0.8.34

 

Same code

2 more contracts

 

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,355,730
Creation transaction
0x022b6533d0…9f7bead8bc

41 files

contracts/core/hub/RIVRPoolManager.sol

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

import {IFeeHook} from "./interfaces/IFeeHook.sol";
import {IValuation} from "./interfaces/IValuation.sol";
import {IHubRegistry} from "./interfaces/IHubRegistry.sol";
import {ISnapshotHook} from "./interfaces/ISnapshotHook.sol";
import {IHoldings, HoldingAccount} from "./interfaces/IHoldings.sol";
import {IAccounting, JournalEntry} from "./interfaces/IAccounting.sol";
import {IHubRequestManager} from "./interfaces/IHubRequestManager.sol";
import {IShareClassManager} from "./interfaces/IShareClassManager.sol";
import {IHub, VaultUpdateKind, AccountType} from "./interfaces/IHub.sol";
import {IHubRequestManagerCallback} from "./interfaces/IHubRequestManagerCallback.sol";

import {Auth} from "../../misc/Auth.sol";
import {d18, D18} from "../../misc/types/D18.sol";
import {Recoverable} from "../../misc/Recoverable.sol";
import {MathLib} from "../../misc/libraries/MathLib.sol";

import {IAdapter} from "../messaging/interfaces/IAdapter.sol";
import {IGateway} from "../messaging/interfaces/IGateway.sol";
import {IMultiAdapter} from "../messaging/interfaces/IMultiAdapter.sol";
import {IHubMessageSender} from "../messaging/interfaces/IGatewaySenders.sol";

import {ICreatePool} from "../../admin/interfaces/ICreatePool.sol";

import {RequestCallbackMessageLib} from "../../vaults/libraries/RequestCallbackMessageLib.sol";

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

/// @title  RIVRPoolManager
/// @notice Central pool management contract, that brings together all functions in one place.
///         Pools can assign pool managers which have full rights over all actions.
contract RIVRPoolManager is BatchedMulticall, Auth, Recoverable, IHub, IHubRequestManagerCallback, ICreatePool {
    using MathLib for uint256;
    using RequestCallbackMessageLib for *;

    IFeeHook public feeHook;
    IHoldings public holdings;
    IAccounting public accounting;
    IHubRegistry public hubRegistry;
    IHubMessageSender public sender;
    IMultiAdapter public multiAdapter;
    IShareClassManager public shareClassManager;

    constructor(
        IGateway gateway_,
        IHoldings holdings_,
        IAccounting accounting_,
        IHubRegistry poolRegistry_,
        IMultiAdapter multiAdapter_,
        IShareClassManager shareClassManager_,
        address deployer
    ) Auth(deployer) BatchedMulticall(gateway_) {
        holdings = holdings_;
        accounting = accounting_;
        hubRegistry = poolRegistry_;
        multiAdapter = multiAdapter_;
        shareClassManager = shareClassManager_;
    }

    //----------------------------------------------------------------------------------------------
    // System methods
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IHub
    function file(bytes32 what, address data) external {
        _auth();

        if (what == "gateway") gateway = IGateway(data);
        else if (what == "feeHook") feeHook = IFeeHook(data);
        else if (what == "holdings") holdings = IHoldings(data);
        else if (what == "sender") sender = IHubMessageSender(data);
        else if (what == "shareClassManager") shareClassManager = IShareClassManager(data);
        else revert FileUnrecognizedParam();
        emit File(what, data);
    }

    /// @inheritdoc ICreatePool
    function createPool(PoolId poolId, address admin, AssetId currency) external payable {
        _auth();

        require(poolId.rivrId() == sender.localRIVRId(), InvalidPoolId());
        hubRegistry.registerPool(poolId, admin, currency);
    }

    //----------------------------------------------------------------------------------------------
    // Pool admin methods
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IHub
    function notifyPool(PoolId poolId, uint16 rivrId, address refund) external payable {
        _isManager(poolId);

        emit NotifyPool(rivrId, poolId);
        sender.sendNotifyPool{value: msgValue()}(rivrId, poolId, refund);
    }

    /// @inheritdoc IHub
    function notifyShareClass(PoolId poolId, ShareClassId scId, uint16 rivrId, bytes32 hook, address refund)
        external
        payable
    {
        _isManager(poolId);

        require(shareClassManager.exists(poolId, scId), IShareClassManager.ShareClassNotFound());

        (string memory name, string memory symbol, bytes32 salt) = shareClassManager.metadata(poolId, scId);
        uint8 decimals = hubRegistry.decimals(poolId);

        emit NotifyShareClass(rivrId, poolId, scId);
        sender.sendNotifyShareClass{value: msgValue()}(
            rivrId, poolId, scId, name, symbol, decimals, salt, hook, refund
        );
    }

    /// @inheritdoc IHub
    function notifyShareMetadata(PoolId poolId, ShareClassId scId, uint16 rivrId, address refund) public payable {
        _isManager(poolId);

        (string memory name, string memory symbol,) = shareClassManager.metadata(poolId, scId);

        emit NotifyShareMetadata(rivrId, poolId, scId, name, symbol);
        sender.sendNotifyShareMetadata{value: msgValue()}(rivrId, poolId, scId, name, symbol, refund);
    }

    /// @inheritdoc IHub
    function updateShareHook(PoolId poolId, ShareClassId scId, uint16 rivrId, bytes32 hook, address refund)
        public
        payable
    {
        _isManager(poolId);

        emit UpdateShareHook(rivrId, poolId, scId, hook);
        sender.sendUpdateShareHook{value: msgValue()}(rivrId, poolId, scId, hook, refund);
    }

    /// @inheritdoc IHub
    function notifySharePrice(PoolId poolId, ShareClassId scId, uint16 rivrId, address refund) public payable {
        _isManager(poolId);

        (D18 pricePoolPerShare, uint64 computedAt) = shareClassManager.pricePoolPerShare(poolId, scId);

        emit NotifySharePrice(rivrId, poolId, scId, pricePoolPerShare, computedAt);
        sender.sendNotifyPricePoolPerShare{value: msgValue()}(
            rivrId, poolId, scId, pricePoolPerShare, computedAt, refund
        );
    }

    /// @inheritdoc IHub
    function notifyAssetPrice(PoolId poolId, ShareClassId scId, AssetId assetId, address refund) public payable {
        _isManager(poolId);

        D18 pricePoolPerAsset_ = pricePoolPerAsset(poolId, scId, assetId);
        emit NotifyAssetPrice(assetId.rivrId(), poolId, scId, assetId, pricePoolPerAsset_);
        sender.sendNotifyPricePoolPerAsset{value: msgValue()}(poolId, scId, assetId, pricePoolPerAsset_, refund);

        if (address(feeHook) != address(0)) feeHook.accrue(poolId, scId);
    }

    /// @inheritdoc IHub
    function setMaxAssetPriceAge(PoolId poolId, ShareClassId scId, AssetId assetId, uint64 maxPriceAge, address refund)
        external
        payable
    {
        _isManager(poolId);

        emit SetMaxAssetPriceAge(poolId, scId, assetId, maxPriceAge);
        sender.sendSetMaxAssetPriceAge{value: msgValue()}(poolId, scId, assetId, maxPriceAge, refund);
    }

    /// @inheritdoc IHub
    function setMaxSharePriceAge(
        PoolId poolId,
        ShareClassId scId,
        uint16 rivrId,
        uint64 maxPriceAge,
        address refund
    ) external payable {
        _isManager(poolId);

        emit SetMaxSharePriceAge(rivrId, poolId, scId, maxPriceAge);
        sender.sendSetMaxSharePriceAge{value: msgValue()}(rivrId, poolId, scId, maxPriceAge, refund);
    }

    /// @inheritdoc IHub
    function setPoolMetadata(PoolId poolId, bytes calldata metadata) external payable {
        _isManager(poolId);

        hubRegistry.setMetadata(poolId, metadata);
    }

    /// @inheritdoc IHub
    function setSnapshotHook(PoolId poolId, ISnapshotHook hook) external payable {
        _isManager(poolId);

        holdings.setSnapshotHook(poolId, hook);
    }

    /// @inheritdoc IHub
    function updateShareClassMetadata(PoolId poolId, ShareClassId scId, string calldata name, string calldata symbol)
        external
        payable
    {
        _isManager(poolId);

        shareClassManager.updateMetadata(poolId, scId, name, symbol);
    }

    /// @inheritdoc IHub
    function updatePoolManager(PoolId poolId, address who, bool canManage) external payable {
        _isManager(poolId);

        hubRegistry.updateManager(poolId, who, canManage);
    }

    /// @inheritdoc IHub
    function setRequestManager(
        PoolId poolId,
        uint16 rivrId,
        IHubRequestManager hubManager,
        bytes32 spokeManager,
        address refund
    ) external payable {
        _isManager(poolId);

        hubRegistry.setHubRequestManager(poolId, rivrId, hubManager);

        emit SetSpokeRequestManager(rivrId, poolId, spokeManager);
        sender.sendSetRequestManager{value: msgValue()}(rivrId, poolId, spokeManager, refund);
    }

    /// @inheritdoc IHub
    function updateBalanceSheetManager(PoolId poolId, uint16 rivrId, bytes32 who, bool canManage, address refund)
        external
        payable
    {
        _isManager(poolId);

        emit UpdateBalanceSheetManager(rivrId, poolId, who, canManage);
        sender.sendUpdateBalanceSheetManager{value: msgValue()}(rivrId, poolId, who, canManage, refund);
    }

    /// @inheritdoc IHub
    function addShareClass(PoolId poolId, string calldata name, string calldata symbol, bytes32 salt)
        external
        returns (ShareClassId scId)
    {
        _isManager(poolId);

        return shareClassManager.addShareClass(poolId, name, symbol, salt);
    }

    /// @inheritdoc IHub
    function updateRestriction(
        PoolId poolId,
        ShareClassId scId,
        uint16 rivrId,
        bytes calldata payload,
        uint128 extraGasLimit,
        address refund
    ) external payable {
        _isManager(poolId);

        require(shareClassManager.exists(poolId, scId), IShareClassManager.ShareClassNotFound());

        emit UpdateRestriction(rivrId, poolId, scId, payload);
        sender.sendUpdateRestriction{value: msgValue()}(rivrId, poolId, scId, payload, extraGasLimit, refund);
    }

    /// @inheritdoc IHub
    function updateVault(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        bytes32 vaultOrFactory,
        VaultUpdateKind kind,
        uint128 extraGasLimit,
        address refund
    ) external payable {
        _isManager(poolId);

        require(shareClassManager.exists(poolId, scId), IShareClassManager.ShareClassNotFound());

        emit UpdateVault(poolId, scId, assetId, vaultOrFactory, kind);
        sender.sendUpdateVault{value: msgValue()}(poolId, scId, assetId, vaultOrFactory, kind, extraGasLimit, refund);
    }

    /// @inheritdoc IHub
    function updateContract(
        PoolId poolId,
        ShareClassId scId,
        uint16 rivrId,
        bytes32 target,
        bytes calldata payload,
        uint128 extraGasLimit,
        address refund
    ) external payable {
        _isManager(poolId);

        require(shareClassManager.exists(poolId, scId), IShareClassManager.ShareClassNotFound());

        emit UpdateContract(rivrId, poolId, scId, target, payload);
        sender.sendTrustedContractUpdate{value: msgValue()}(
            rivrId, poolId, scId, target, payload, extraGasLimit, refund
        );
    }

    /// @inheritdoc IHub
    function updateSharePrice(PoolId poolId, ShareClassId scId, D18 pricePoolPerShare, uint64 computedAt)
        public
        payable
    {
        _isManager(poolId);

        shareClassManager.updateSharePrice(poolId, scId, pricePoolPerShare, computedAt);

        if (address(feeHook) != address(0)) feeHook.accrue(poolId, scId);
    }

    /// @inheritdoc IHub
    function initializeHolding(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        IValuation valuation,
        AccountId assetAccount,
        AccountId equityAccount,
        AccountId gainAccount,
        AccountId lossAccount
    ) external payable {
        _isManager(poolId);

        require(hubRegistry.isRegistered(assetId), IHubRegistry.AssetNotFound());
        require(
            assetAccount != equityAccount && assetAccount != gainAccount && assetAccount != lossAccount,
            IHub.InvalidAccountCombination()
        );
        require(
            accounting.exists(poolId, assetAccount) && accounting.exists(poolId, equityAccount)
                && accounting.exists(poolId, lossAccount) && accounting.exists(poolId, gainAccount),
            IAccounting.AccountDoesNotExist()
        );

        holdings.initialize(
            poolId,
            scId,
            assetId,
            valuation,
            false,
            holdingAccounts(assetAccount, equityAccount, gainAccount, lossAccount)
        );

        // If increase/decrease was called before initialize, we add journal entries for this
        _updateAccountingAmount(poolId, scId, assetId, true, holdings.value(poolId, scId, assetId));
    }

    /// @inheritdoc IHub
    function initializeLiability(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        IValuation valuation,
        AccountId expenseAccount,
        AccountId liabilityAccount
    ) external payable {
        _isManager(poolId);

        require(hubRegistry.isRegistered(assetId), IHubRegistry.AssetNotFound());
        require(expenseAccount != liabilityAccount, IHub.InvalidAccountCombination());
        require(
            accounting.exists(poolId, expenseAccount) && accounting.exists(poolId, liabilityAccount),
            IAccounting.AccountDoesNotExist()
        );

        holdings.initialize(poolId, scId, assetId, valuation, true, liabilityAccounts(expenseAccount, liabilityAccount));

        // If increase/decrease was called before initialize, we add journal entries for this
        _updateAccountingAmount(poolId, scId, assetId, true, holdings.value(poolId, scId, assetId));
    }

    /// @inheritdoc IHub
    function updateHoldingValue(PoolId poolId, ShareClassId scId, AssetId assetId) public payable {
        _isManager(poolId);

        (bool isPositive, uint128 diff) = holdings.update(poolId, scId, assetId);
        _updateAccountingValue(poolId, scId, assetId, isPositive, diff);

        holdings.callOnSyncSnapshot(poolId, scId, assetId.rivrId());
    }

    /// @inheritdoc IHub
    function updateHoldingValuation(PoolId poolId, ShareClassId scId, AssetId assetId, IValuation valuation)
        external
        payable
    {
        _isManager(poolId);

        holdings.updateValuation(poolId, scId, assetId, valuation);
    }

    /// @inheritdoc IHub
    function updateHoldingIsLiability(PoolId poolId, ShareClassId scId, AssetId assetId, bool isLiability)
        external
        payable
    {
        _isManager(poolId);

        holdings.updateIsLiability(poolId, scId, assetId, isLiability);
    }

    /// @inheritdoc IHub
    function setHoldingAccountId(PoolId poolId, ShareClassId scId, AssetId assetId, uint8 kind, AccountId accountId)
        external
        payable
    {
        _isManager(poolId);

        require(accounting.exists(poolId, accountId), IAccounting.AccountDoesNotExist());

        holdings.setAccountId(poolId, scId, assetId, kind, accountId);
    }

    /// @inheritdoc IHub
    function createAccount(PoolId poolId, AccountId account, bool isDebitNormal) public payable {
        _isManager(poolId);

        accounting.createAccount(poolId, account, isDebitNormal);
    }

    /// @inheritdoc IHub
    function setAccountMetadata(PoolId poolId, AccountId account, bytes calldata metadata) external payable {
        _isManager(poolId);

        accounting.setAccountMetadata(poolId, account, metadata);
    }

    /// @inheritdoc IHub
    function updateJournal(PoolId poolId, JournalEntry[] memory debits, JournalEntry[] memory credits)
        external
        payable
    {
        _isManager(poolId);

        accounting.unlock(poolId);
        accounting.addJournal(debits, credits);
        accounting.lock();
    }

    /// @inheritdoc IHub
    function setAdapters(
        PoolId poolId,
        uint16 rivrId,
        IAdapter[] memory localAdapters,
        bytes32[] memory remoteAdapters,
        uint8 threshold,
        uint8 recoveryIndex,
        address refund
    ) external payable {
        _isManager(poolId);

        multiAdapter.setAdapters(rivrId, poolId, localAdapters, threshold, recoveryIndex);

        sender.sendSetPoolAdapters{value: msgValue()}(
            rivrId, poolId, remoteAdapters, threshold, recoveryIndex, refund
        );
    }

    /// @inheritdoc IHub
    function updateGatewayManager(PoolId poolId, uint16 rivrId, bytes32 who, bool canManage, address refund)
        external
        payable
    {
        _isManager(poolId);

        sender.sendUpdateGatewayManager{value: msgValue()}(rivrId, poolId, who, canManage, refund);
    }

    //----------------------------------------------------------------------------------------------
    // Request manager callback
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IHubRequestManagerCallback
    function requestCallback(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        bytes calldata payload,
        uint128 extraGasLimit,
        bool unpaidMode,
        address refund
    ) external payable {
        IHubRequestManager manager = hubRegistry.hubRequestManager(poolId, assetId.rivrId());
        require(address(manager) != address(0), InvalidRequestManager());
        require(msg.sender == address(manager), NotAuthorized());

        sender.sendRequestCallback{value: msgValue()}(poolId, scId, assetId, payload, extraGasLimit, unpaidMode, refund);
    }

    //----------------------------------------------------------------------------------------------
    //  Accounting methods
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IHub
    /// @notice Create credit & debit entries for the deposit or withdrawal of a holding.
    ///         This updates the asset/expense as well as the equity/liability accounts.
    function updateAccountingAmount(PoolId poolId, ShareClassId scId, AssetId assetId, bool isPositive, uint128 diff)
        external
        payable
        auth
    {
        _updateAccountingAmount(poolId, scId, assetId, isPositive, diff);
    }

    function _updateAccountingAmount(PoolId poolId, ShareClassId scId, AssetId assetId, bool isPositive, uint128 diff)
        internal
    {
        if (diff == 0) return;

        accounting.unlock(poolId);

        bool isLiability = holdings.isLiability(poolId, scId, assetId);
        AccountType debitAccountType = isLiability ? AccountType.Expense : AccountType.Asset;
        AccountType creditAccountType = isLiability ? AccountType.Liability : AccountType.Equity;

        if (isPositive) {
            accounting.addDebit(holdings.accountId(poolId, scId, assetId, uint8(debitAccountType)), diff);
            accounting.addCredit(holdings.accountId(poolId, scId, assetId, uint8(creditAccountType)), diff);
        } else {
            accounting.addDebit(holdings.accountId(poolId, scId, assetId, uint8(creditAccountType)), diff);
            accounting.addCredit(holdings.accountId(poolId, scId, assetId, uint8(debitAccountType)), diff);
        }

        accounting.lock();
    }

    /// @inheritdoc IHub
    /// @notice Create credit & debit entries for the increase or decrease in the value of a holding.
    ///         This updates the asset/expense as well as the gain/loss accounts.
    function updateAccountingValue(PoolId poolId, ShareClassId scId, AssetId assetId, bool isPositive, uint128 diff)
        external
        payable
        auth
    {
        _updateAccountingValue(poolId, scId, assetId, isPositive, diff);
    }

    function _updateAccountingValue(PoolId poolId, ShareClassId scId, AssetId assetId, bool isPositive, uint128 diff)
        internal
    {
        if (diff == 0) return;

        accounting.unlock(poolId);

        // Save a diff=0 update gas cost
        if (isPositive) {
            if (holdings.isLiability(poolId, scId, assetId)) {
                accounting.addCredit(holdings.accountId(poolId, scId, assetId, uint8(AccountType.Liability)), diff);
                accounting.addDebit(holdings.accountId(poolId, scId, assetId, uint8(AccountType.Expense)), diff);
            } else {
                accounting.addCredit(holdings.accountId(poolId, scId, assetId, uint8(AccountType.Gain)), diff);
                accounting.addDebit(holdings.accountId(poolId, scId, assetId, uint8(AccountType.Asset)), diff);
            }
        } else {
            if (holdings.isLiability(poolId, scId, assetId)) {
                accounting.addCredit(holdings.accountId(poolId, scId, assetId, uint8(AccountType.Expense)), diff);
                accounting.addDebit(holdings.accountId(poolId, scId, assetId, uint8(AccountType.Liability)), diff);
            } else {
                accounting.addCredit(holdings.accountId(poolId, scId, assetId, uint8(AccountType.Asset)), diff);
                accounting.addDebit(holdings.accountId(poolId, scId, assetId, uint8(AccountType.Loss)), diff);
            }
        }

        accounting.lock();
    }

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

    /// @inheritdoc IHub
    function holdingAccounts(
        AccountId assetAccount,
        AccountId equityAccount,
        AccountId gainAccount,
        AccountId lossAccount
    ) public pure returns (HoldingAccount[] memory) {
        HoldingAccount[] memory accounts = new HoldingAccount[](4);
        accounts[0] = HoldingAccount(assetAccount, uint8(AccountType.Asset));
        accounts[1] = HoldingAccount(equityAccount, uint8(AccountType.Equity));
        accounts[2] = HoldingAccount(gainAccount, uint8(AccountType.Gain));
        accounts[3] = HoldingAccount(lossAccount, uint8(AccountType.Loss));
        return accounts;
    }

    /// @inheritdoc IHub
    function liabilityAccounts(AccountId expenseAccount, AccountId liabilityAccount)
        public
        pure
        returns (HoldingAccount[] memory)
    {
        HoldingAccount[] memory accounts = new HoldingAccount[](2);
        accounts[0] = HoldingAccount(expenseAccount, uint8(AccountType.Expense));
        accounts[1] = HoldingAccount(liabilityAccount, uint8(AccountType.Liability));
        return accounts;
    }

    /// @inheritdoc IHub
    function pricePoolPerAsset(PoolId poolId, ShareClassId scId, AssetId assetId) public view returns (D18) {
        // Assume price of 1.0 if the holding is not initialized yet
        if (!holdings.isInitialized(poolId, scId, assetId)) return d18(1, 1);

        IValuation valuation = holdings.valuation(poolId, scId, assetId);
        return valuation.getPrice(poolId, scId, assetId);
    }

    //----------------------------------------------------------------------------------------------
    //  Internal methods
    //----------------------------------------------------------------------------------------------

    /// @dev Ensure the sender is authorized
    function _auth() internal auth {}

    /// @dev Ensure the sender is a pool admin
    function _isManager(PoolId poolId) internal view {
        require(hubRegistry.manager(poolId, msgSender()), IHub.NotManager());
    }
}

contracts/admin/interfaces/ICreatePool.sol

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

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

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

contracts/core/hub/interfaces/IAccounting.sol

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

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

struct JournalEntry {
    uint128 value;
    AccountId accountId;
}

/// @title  IAccounting
/// @notice Double-entry accounting system for pool financial operations
/// @dev    Manages debits, credits, and account balances with journal entry tracking
interface IAccounting {
    /// @notice Emitted when a an entry is done
    event Credit(PoolId indexed poolId, AccountId indexed account, uint128 value);
    event Debit(PoolId indexed poolId, AccountId indexed account, uint128 value);

    /// @notice Emitted at the beginning and end of a journal entry
    event StartJournalId(PoolId indexed poolId, uint256 journalId);
    event EndJournalId(PoolId indexed poolId, uint256 journalId);

    /// @notice Emitted when a new account is created
    event CreateAccount(PoolId indexed poolId, AccountId indexed account, bool isDebitNormal);

    /// @notice Emitted when metadata is set for an account
    event SetAccountMetadata(PoolId indexed poolId, AccountId indexed account, bytes metadata);

    /// @notice Dispatched when the pool is already unlocked.
    error AccountingAlreadyUnlocked();

    /// @notice Dispatched when the pool is not unlocked to interact with.
    error AccountingLocked();

    /// @notice Dispatched when the debit and credit side do not match at the end of a transaction.
    error Unbalanced();

    /// @notice Dispatched when trying to create an account that already exists.
    error AccountExists();

    /// @notice Dispatched when trying debit or credit an account that doesn't exists.
    error AccountDoesNotExist();

    /// @notice Represents an account
    struct Account {
        uint128 totalDebit;
        uint128 totalCredit;
        bool isDebitNormal;
        uint64 lastUpdated;
        bytes metadata;
    }

    /// @notice Debits an account. Increase the value of debit-normal accounts, decrease for credit-normal ones.
    /// @param account The account to debit
    /// @param value Amount being debited
    function addDebit(AccountId account, uint128 value) external;

    /// @notice Credits an account. Decrease the value of debit-normal accounts, increase for credit-normal ones.
    /// @param account The account to credit
    /// @param value Amount being credited
    function addCredit(AccountId account, uint128 value) external;

    /// @notice Apply addDebit and addCredit to each journal entry
    function addJournal(JournalEntry[] memory debits, JournalEntry[] memory credits) external;

    /// @notice Unlocks a pool for journal entries
    /// @param poolId The pool to unlock
    function unlock(PoolId poolId) external;

    /// @notice Closes the transaction and checks if the entries are balanced.
    function lock() external;

    /// @notice Creates an account.
    /// @param poolId The pool the account belongs to
    /// @param account The account to create
    /// @param isDebitNormal Whether the account is debit-normal or credit-normal
    function createAccount(PoolId poolId, AccountId account, bool isDebitNormal) external;

    /// @notice Sets metadata associated to an existent account.
    /// @param poolId The pool the account belongs to
    /// @param account The account to set metadata for
    /// @param metadata The metadata to set
    function setAccountMetadata(PoolId poolId, AccountId account, bytes calldata metadata) external;

    /// @notice Returns the value of an account
    /// @param poolId The pool the account belongs to
    /// @param account The account to get the value of
    /// @return isPositive Indicates whether value is a positive or negative value
    /// @return value The value of the account
    function accountValue(PoolId poolId, AccountId account) external view returns (bool isPositive, uint128 value);

    /// @notice Returns whether an account exists
    /// @param poolId The pool the account belongs to
    /// @param account The account to check
    /// @return True if the account exists, false otherwise
    function exists(PoolId poolId, AccountId account) external view returns (bool);
}

contracts/core/hub/interfaces/IFeeHook.sol

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

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

interface IFeeHook {
    /// @notice Accrue the fee amount for a specific pool and share class.
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    function accrue(PoolId poolId, ShareClassId scId) external;

    /// @notice Returns the accrued fees, denominated in pool units.
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @return poolAmount The accrued fee amount in pool units
    function accrued(PoolId poolId, ShareClassId scId) external view returns (uint128 poolAmount);
}

contracts/core/hub/interfaces/IHoldings.sol

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

import {IValuation} from "./IValuation.sol";
import {ISnapshotHook} from "./ISnapshotHook.sol";

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

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

struct Holding {
    uint128 assetAmount;
    uint128 assetAmountValue;
    IValuation valuation; // Used for existence
    bool isLiability;
}

struct HoldingAccount {
    AccountId accountId;
    uint8 kind;
}

struct Snapshot {
    /// @notice Indicates if the current accounting state is a correct snapshot of the balance sheet state, i.e. asset
    ///         and/or share amounts are in sync between Hub and Spoke
    bool isSnapshot;
    /// @notice The nonce of the snapshot. Incremented after each snapshot is taken.
    uint64 nonce;
}

interface IHoldings {
    //----------------------------------------------------------------------------------------------
    // Events
    //----------------------------------------------------------------------------------------------

    /// @notice Emitted when a holding is initialized
    event Initialize(
        PoolId indexed,
        ShareClassId indexed scId,
        AssetId indexed assetId,
        IValuation valuation,
        bool isLiability,
        HoldingAccount[] accounts
    );

    /// @notice Emitted when a holding is increased
    event Increase(
        PoolId indexed,
        ShareClassId indexed scId,
        AssetId indexed assetId,
        D18 pricePoolPerAsset,
        uint128 amount,
        uint128 increasedValue
    );

    /// @notice Emitted when a holding is decreased
    event Decrease(
        PoolId indexed,
        ShareClassId indexed scId,
        AssetId indexed assetId,
        D18 pricePoolPerAsset,
        uint128 amount,
        uint128 decreasedValue
    );

    /// @notice Emitted when the holding is updated
    event Update(
        PoolId indexed poolId, ShareClassId indexed scId, AssetId indexed assetId, bool isPositive, uint128 diffValue
    );

    /// @notice Emitted when a holding valuation is updated
    event UpdateValuation(
        PoolId indexed poolId, ShareClassId indexed scId, AssetId indexed assetId, IValuation valuation
    );

    /// @notice Emitted when a holding is updated to a liability, or vice versa
    event UpdateIsLiability(
        PoolId indexed poolId, ShareClassId indexed scId, AssetId indexed assetId, bool isLiability
    );

    /// @notice Emitted when an account is for a holding is set
    event SetAccountId(
        PoolId indexed poolId, ShareClassId indexed scId, AssetId indexed assetId, uint8 kind, AccountId accountId
    );

    /// @notice Emitted when an snapshot hook for a pool ID is set
    event SetSnapshotHook(PoolId indexed poolId, ISnapshotHook hook);

    /// @notice Emitted when the snapshot state is updated
    event SetSnapshot(
        PoolId indexed poolId, ShareClassId indexed scId, uint16 indexed rivrId, bool isSnapshot, uint64 nonce
    );

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

    /// @notice Item was not found for a required action.
    error HoldingNotFound();

    /// @notice Valuation is not valid.
    error WrongValuation();

    /// @notice ShareClassId is not valid.
    error WrongShareClassId();

    /// @notice AssetId is not valid.
    error WrongAssetId();

    /// @notice Holding was already initialized.
    error AlreadyInitialized();

    error InvalidNonce(uint64 expected, uint64 actual);

    error HoldingNotZero();

    //----------------------------------------------------------------------------------------------
    // Holding creation & updates
    //----------------------------------------------------------------------------------------------

    /// @notice Initializes a new holding in a pool using a valuation
    /// @dev `increase()` and `decrease()` can be called before initialize
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @param valuation The valuation contract to use for pricing
    /// @param isLiability Whether this holding represents a liability
    /// @param accounts Array of holding accounts to initialize
    function initialize(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        IValuation valuation,
        bool isLiability,
        HoldingAccount[] memory accounts
    ) external;

    /// @notice Increments the amount of a holding and updates the value for that increment
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @param pricePoolPerAsset The price of one asset unit in terms of pool currency
    /// @param amount Amount to increase by
    /// @return value The value the holding has incremented
    function increase(PoolId poolId, ShareClassId scId, AssetId assetId, D18 pricePoolPerAsset, uint128 amount)
        external
        returns (uint128 value);

    /// @notice Decrements the amount of a holding and updates the value for that decrement
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @param pricePoolPerAsset The price of one asset unit in terms of pool currency
    /// @param amount Amount to decrease by
    /// @return value The value the holding has decremented
    function decrease(PoolId poolId, ShareClassId scId, AssetId assetId, D18 pricePoolPerAsset, uint128 amount)
        external
        returns (uint128 value);

    /// @notice Reset the value of a holding using the current valuation
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @return isPositive Indicates whether the diffValue is positive or negative
    /// @return diffValue The difference in value after the new valuation
    function update(PoolId poolId, ShareClassId scId, AssetId assetId)
        external
        returns (bool isPositive, uint128 diffValue);

    /// @notice Updates the valuation method used for this holding
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @param valuation The new valuation contract to use
    function updateValuation(PoolId poolId, ShareClassId scId, AssetId assetId, IValuation valuation) external;

    /// @notice Updates whether the holding is a liability
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @param isLiability Whether this holding is a liability
    function updateIsLiability(PoolId poolId, ShareClassId scId, AssetId assetId, bool isLiability) external;

    /// @notice Sets an account id for a specific kind
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @param kind The account type/kind
    /// @param accountId The account identifier to set
    function setAccountId(PoolId poolId, ShareClassId scId, AssetId assetId, uint8 kind, AccountId accountId) external;

    /// @notice Sets the snapshot state for a share class on a specific network
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param rivrId The network identifier
    /// @param isSnapshot Whether the state is a snapshot
    /// @param nonce The snapshot nonce for validation
    function setSnapshot(PoolId poolId, ShareClassId scId, uint16 rivrId, bool isSnapshot, uint64 nonce) external;

    /// @notice Sets the snapshot hook for a pool
    /// @param poolId The pool identifier
    /// @param hook The snapshot hook contract
    function setSnapshotHook(PoolId poolId, ISnapshotHook hook) external;

    /// @notice Checks the snapshot state and calls the hook if it's a snapshot
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param rivrId The network identifier
    function callOnSyncSnapshot(PoolId poolId, ShareClassId scId, uint16 rivrId) external;

    /// @notice Calls the snapshot hook's onTransfer function if a hook is set
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param originRIVRId The origin network identifier
    /// @param targetRIVRId The target network identifier
    /// @param amount The amount of shares transferred
    function callOnTransferSnapshot(
        PoolId poolId,
        ShareClassId scId,
        uint16 originRIVRId,
        uint16 targetRIVRId,
        uint128 amount
    ) external;

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

    /// @notice Returns the snapshot hook for the given pool
    /// @param poolId The pool identifier
    /// @return The snapshot hook contract
    function snapshotHook(PoolId poolId) external view returns (ISnapshotHook);

    /// @notice Returns the snapshot info for a given pool, share class and rivrId
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param rivrId The network identifier
    /// @return isSnapshot Whether the state is a snapshot
    /// @return nonce The current snapshot nonce
    function snapshot(PoolId poolId, ShareClassId scId, uint16 rivrId)
        external
        view
        returns (bool isSnapshot, uint64 nonce);

    /// @notice Returns the value of this holding
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @return value The current value of the holding
    function value(PoolId poolId, ShareClassId scId, AssetId assetId) external view returns (uint128 value);

    /// @notice Returns the amount of this holding
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @return amount The current amount of the holding
    function amount(PoolId poolId, ShareClassId scId, AssetId assetId) external view returns (uint128 amount);

    /// @notice Returns the valuation method used for this holding
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @return The valuation contract
    function valuation(PoolId poolId, ShareClassId scId, AssetId assetId) external view returns (IValuation);

    /// @notice Returns if the holding is a liability
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @return Whether the holding is a liability
    function isLiability(PoolId poolId, ShareClassId scId, AssetId assetId) external view returns (bool);

    /// @notice Returns an account id for a specific kind
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @param kind The account type/kind
    /// @return The account identifier
    function accountId(PoolId poolId, ShareClassId scId, AssetId assetId, uint8 kind) external view returns (AccountId);

    /// @notice Tells if the holding was initialized for an asset in a share class
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @return Whether the holding is initialized
    function isInitialized(PoolId poolId, ShareClassId scId, AssetId assetId) external view returns (bool);
}

contracts/core/hub/interfaces/IHub.sol

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

import {IValuation} from "./IValuation.sol";
import {IHubRegistry} from "./IHubRegistry.sol";
import {ISnapshotHook} from "./ISnapshotHook.sol";
import {IHoldings, HoldingAccount} from "./IHoldings.sol";
import {IAccounting, JournalEntry} from "./IAccounting.sol";
import {IHubRequestManager} from "./IHubRequestManager.sol";
import {IShareClassManager} from "./IShareClassManager.sol";

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

import {IAdapter} from "../../messaging/interfaces/IAdapter.sol";
import {VaultUpdateKind} from "../../messaging/libraries/MessageLib.sol";
import {IHubMessageSender} from "../../messaging/interfaces/IGatewaySenders.sol";

import {PoolId} from "../../types/PoolId.sol";
import {AssetId} from "../../types/AssetId.sol";
import {AccountId} from "../../types/AccountId.sol";
import {ShareClassId} from "../../types/ShareClassId.sol";
import {IBatchedMulticall} from "../../utils/interfaces/IBatchedMulticall.sol";

/// @notice Account types used by Hub
enum AccountType {
    /// @notice Account for tracking assets
    Asset,
    /// @notice Account for tracking equities
    Equity,
    /// @notice Account for tracking losses
    Loss,
    /// @notice Account for tracking profits
    Gain,
    /// @notice Account for tracking expenses
    Expense,
    /// @notice Account for tracking liabilities
    Liability
}

/// @notice Interface with all methods available in the system used by actors
interface IHub is IBatchedMulticall {
    //----------------------------------------------------------------------------------------------
    // Events
    //----------------------------------------------------------------------------------------------

    event NotifyPool(uint16 indexed rivrId, PoolId indexed poolId);
    event NotifyShareClass(uint16 indexed rivrId, PoolId indexed poolId, ShareClassId scId);
    event NotifyShareMetadata(
        uint16 indexed rivrId, PoolId indexed poolId, ShareClassId scId, string name, string symbol
    );
    event UpdateShareHook(uint16 indexed rivrId, PoolId indexed poolId, ShareClassId scId, bytes32 hook);
    event NotifySharePrice(
        uint16 indexed rivrId, PoolId indexed poolId, ShareClassId scId, D18 poolPerShare, uint64 computedAt
    );
    event NotifyAssetPrice(
        uint16 indexed rivrId, PoolId indexed poolId, ShareClassId scId, AssetId assetId, D18 pricePoolPerAsset
    );
    event UpdateRestriction(uint16 indexed rivrId, PoolId indexed poolId, ShareClassId scId, bytes payload);
    event SetSpokeRequestManager(uint16 indexed rivrId, PoolId indexed poolId, bytes32 indexed manager);
    event UpdateBalanceSheetManager(
        uint16 indexed rivrId, PoolId indexed poolId, bytes32 indexed manager, bool canManage
    );
    event UpdateVault(
        PoolId indexed poolId, ShareClassId scId, AssetId assetId, bytes32 vaultOrFactory, VaultUpdateKind kind
    );
    event UpdateContract(
        uint16 indexed rivrId, PoolId indexed poolId, ShareClassId scId, bytes32 target, bytes payload
    );
    event SetMaxAssetPriceAge(PoolId indexed poolId, ShareClassId scId, AssetId assetId, uint64 maxPriceAge);
    event SetMaxSharePriceAge(
        uint16 indexed rivrId, PoolId indexed poolId, ShareClassId scId, uint64 maxPriceAge
    );
    event ForwardTransferShares(
        uint16 indexed fromRIVRId,
        uint16 indexed toRIVRId,
        PoolId indexed poolId,
        ShareClassId scId,
        bytes32 receiver,
        uint128 amount
    );
    /// @notice Emitted when a call to `file()` was performed.
    event File(bytes32 what, address addr);

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

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

    /// @notice Dispatched when the pool is already unlocked.
    ///         It means when calling to `execute()` inside `execute()`.
    error PoolAlreadyUnlocked();

    /// @notice Dispatched when the pool can not be unlocked by the caller
    error NotManager();

    /// @notice Dispatched when an invalid rivr ID is set in the pool ID.
    error InvalidPoolId();

    /// @notice Dispatched when an invalid combination of account IDs is passed.
    error InvalidAccountCombination();

    error InvalidRequestManager();

    error RequestManagerCallFailed();

    //----------------------------------------------------------------------------------------------
    // System methods
    //----------------------------------------------------------------------------------------------

    /// @notice Returns the holdings contract
    /// @return The holdings contract instance
    function holdings() external view returns (IHoldings);

    /// @notice Returns the accounting contract
    /// @return The accounting contract instance
    function accounting() external view returns (IAccounting);

    /// @notice Returns the hub registry contract
    /// @return The hub registry contract instance
    function hubRegistry() external view returns (IHubRegistry);

    /// @notice Returns the message sender contract
    /// @return The message sender contract instance
    function sender() external view returns (IHubMessageSender);

    /// @notice Returns the share class manager contract
    /// @return The share class manager contract instance
    function shareClassManager() external view returns (IShareClassManager);

    /// @notice Updates a contract parameter
    /// @param what Name of the parameter to update (accepts 'hubRegistry', 'accounting', 'holdings', 'gateway', 'sender')
    /// @param data Address of the new contract
    function file(bytes32 what, address data) external;

    //----------------------------------------------------------------------------------------------
    // Pool admin methods
    //----------------------------------------------------------------------------------------------

    /// @notice Notify to a CV instance that a new pool is available
    /// @param poolId The pool identifier
    /// @param rivrId Chain where CV instance lives
    /// @param refund Address to receive excess gas refund
    function notifyPool(PoolId poolId, uint16 rivrId, address refund) external payable;

    /// @notice Notify to a CV instance that a new share class is available
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param rivrId Chain where CV instance lives
    /// @param hook The hook address of the share class
    /// @param refund Address to receive excess gas refund
    function notifyShareClass(PoolId poolId, ShareClassId scId, uint16 rivrId, bytes32 hook, address refund)
        external
        payable;

    /// @notice Notify to a CV instance that share metadata has updated
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param rivrId Chain where CV instance lives
    /// @param refund Address to receive excess gas refund
    function notifyShareMetadata(PoolId poolId, ShareClassId scId, uint16 rivrId, address refund) external payable;

    /// @notice Update on a CV instance the hook of a share token
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param rivrId Chain where CV instance lives
    /// @param hook The new hook address
    /// @param refund Address to receive excess gas refund
    function updateShareHook(PoolId poolId, ShareClassId scId, uint16 rivrId, bytes32 hook, address refund)
        external
        payable;

    /// @notice Notify to a CV instance the latest available price in POOL_UNIT / SHARE_UNIT
    /// @param poolId The pool identifier
    /// @param scId Identifier of the share class
    /// @param rivrId Chain to where the share price is notified
    /// @param refund Address to receive excess gas refund
    function notifySharePrice(PoolId poolId, ShareClassId scId, uint16 rivrId, address refund) external payable;

    /// @notice Notify to a CV instance the latest available price in POOL_UNIT / ASSET_UNIT
    /// @param poolId The pool identifier
    /// @param scId Identifier of the share class
    /// @param assetId Identifier of the asset
    /// @param refund Address to receive excess gas refund
    function notifyAssetPrice(PoolId poolId, ShareClassId scId, AssetId assetId, address refund) external payable;

    /// @notice Set the max price age per asset of a share class
    /// @param poolId The rivr pool id
    /// @param scId The share class id
    /// @param assetId The asset id
    /// @param maxPriceAge Timestamp until the price become invalid
    /// @param refund Address to receive excess gas refund
    function setMaxAssetPriceAge(PoolId poolId, ShareClassId scId, AssetId assetId, uint64 maxPriceAge, address refund)
        external
        payable;

    /// @notice Set the max price age per share of a share class
    /// @param poolId The rivr pool id
    /// @param scId The share class id
    /// @param rivrId Chain where CV instance lives
    /// @param maxPriceAge Timestamp until the price become invalid
    /// @param refund Address to receive excess gas refund
    function setMaxSharePriceAge(
        PoolId poolId,
        ShareClassId scId,
        uint16 rivrId,
        uint64 maxPriceAge,
        address refund
    ) external payable;

    /// @notice Attach custom data to a pool
    /// @param poolId The pool identifier
    /// @param metadata Custom metadata to attach
    function setPoolMetadata(PoolId poolId, bytes calldata metadata) external payable;

    /// @notice Set snapshot hook for a pool
    /// @param poolId The pool identifier
    /// @param hook The snapshot hook contract
    function setSnapshotHook(PoolId poolId, ISnapshotHook hook) external payable;

    /// @notice Update name & symbol of share class
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param name New name for the share class
    /// @param symbol New symbol for the share class
    function updateShareClassMetadata(PoolId poolId, ShareClassId scId, string calldata name, string calldata symbol)
        external
        payable;

    /// @notice Allow/disallow an account to interact as hub manager this pool
    /// @param poolId The pool identifier
    /// @param who Address to update manager status for
    /// @param canManage Whether the address can manage the pool
    function updatePoolManager(PoolId poolId, address who, bool canManage) external payable;

    /// @notice Allow/disallow an account to interact as request manager
    /// @param poolId The pool identifier
    /// @param rivrId Chain where the request manager will operate
    /// @param hubManager Hub request manager contract
    /// @param spokeManager Spoke request manager address
    /// @param refund Address to receive excess gas refund
    function setRequestManager(
        PoolId poolId,
        uint16 rivrId,
        IHubRequestManager hubManager,
        bytes32 spokeManager,
        address refund
    ) external payable;

    /// @notice Allow/disallow an account to interact as balance sheet manager for this pool
    /// @param poolId The pool identifier
    /// @param rivrId Chain where the balance sheet manager will operate
    /// @param who Address to update manager status for
    /// @param canManage Whether the address can manage the balance sheet
    /// @param refund Address to receive excess gas refund
    function updateBalanceSheetManager(PoolId poolId, uint16 rivrId, bytes32 who, bool canManage, address refund)
        external
        payable;

    /// @notice Add a new share class to the pool
    /// @param poolId The pool identifier
    /// @param name Name for the share class
    /// @param symbol Symbol for the share class
    /// @param salt Salt for deterministic deployment
    /// @return scId The newly created share class identifier
    function addShareClass(PoolId poolId, string calldata name, string calldata symbol, bytes32 salt)
        external
        returns (ShareClassId scId);

    /// @notice Update remotely a restriction
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param rivrId Chain where CV instance lives
    /// @param payload Content of the restriction update to execute
    /// @param extraGasLimit Extra gas limit for remote computation
    /// @param refund Address to receive excess gas refund
    function updateRestriction(
        PoolId poolId,
        ShareClassId scId,
        uint16 rivrId,
        bytes calldata payload,
        uint128 extraGasLimit,
        address refund
    ) external payable;

    /// @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
    /// @param extraGasLimit Extra gas limit for remote computation
    /// @param refund Address to receive excess gas refund
    function updateVault(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        bytes32 vaultOrFactory,
        VaultUpdateKind kind,
        uint128 extraGasLimit,
        address refund
    ) external payable;

    /// @notice Update remotely an existing vault
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param rivrId Chain where CV instance lives
    /// @param target Contract where to execute in CV
    /// @param payload Content of the update to execute
    /// @param extraGasLimit Extra gas limit for remote computation
    /// @param refund Address to receive excess gas refund
    function updateContract(
        PoolId poolId,
        ShareClassId scId,
        uint16 rivrId,
        bytes32 target,
        bytes calldata payload,
        uint128 extraGasLimit,
        address refund
    ) external payable;

    /// @notice Update the price per share of a share class
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param pricePoolPerShare The new price per share
    /// @param computedAt Timestamp when the price was computed (must be <= block.timestamp)
    function updateSharePrice(PoolId poolId, ShareClassId scId, D18 pricePoolPerShare, uint64 computedAt)
        external
        payable;

    /// @notice Create a new holding associated to the asset in a share class.
    ///         It will register the different accounts used for holdings.
    ///         The accounts have to be created beforehand.
    ///         The same account can be used for different kinds.
    ///         e.g.: The equity, gain, and loss account can be the same account.
    ///         They can also be shared across assets.
    ///         e.g.: All assets can use the same equity account.
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @param valuation Used to transform between payment assets and pool currency
    /// @param assetAccount Used to track the asset value
    /// @param equityAccount Used to track the equity value
    /// @param gainAccount Used to track the gain value
    /// @param lossAccount Used to track the loss value
    function initializeHolding(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        IValuation valuation,
        AccountId assetAccount,
        AccountId equityAccount,
        AccountId gainAccount,
        AccountId lossAccount
    ) external payable;

    /// @notice Create a new liability associated to the asset in a share class.
    ///         It will register the different accounts used for holdings.
    ///         The accounts have to be created beforehand.
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @param valuation Used to transform between the holding asset and pool currency
    /// @param expenseAccount Used to track the expense value
    /// @param liabilityAccount Used to track the liability value
    function initializeLiability(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        IValuation valuation,
        AccountId expenseAccount,
        AccountId liabilityAccount
    ) external payable;

    /// @notice Updates the pool currency value of this holding based of the associated valuation
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    function updateHoldingValue(PoolId poolId, ShareClassId scId, AssetId assetId) external payable;

    /// @notice Updates whether the holding represents a liability or not
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @param isLiability Whether the holding is a liability
    function updateHoldingIsLiability(PoolId poolId, ShareClassId scId, AssetId assetId, bool isLiability)
        external
        payable;

    /// @notice Updates the valuation used by a holding
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @param valuation Used to transform between the holding asset and pool currency
    function updateHoldingValuation(PoolId poolId, ShareClassId scId, AssetId assetId, IValuation valuation)
        external
        payable;

    /// @notice Set an account of a holding
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @param kind The account type
    /// @param accountId The account identifier to set
    function setHoldingAccountId(PoolId poolId, ShareClassId scId, AssetId assetId, uint8 kind, AccountId accountId)
        external
        payable;

    /// @notice Creates an account
    /// @param poolId The pool identifier
    /// @param accountId The new AccountId used
    /// @param isDebitNormal Determines if the account should be used as debit-normal or credit-normal
    function createAccount(PoolId poolId, AccountId accountId, bool isDebitNormal) external payable;

    /// @notice Attach custom data to an account
    /// @param poolId The pool identifier
    /// @param account The account identifier
    /// @param metadata Custom metadata to attach
    function setAccountMetadata(PoolId poolId, AccountId account, bytes calldata metadata) external payable;

    /// @notice Perform an accounting entries update
    /// @param poolId The pool identifier
    /// @param debits Array of debit journal entries
    /// @param credits Array of credit journal entries
    function updateJournal(PoolId poolId, JournalEntry[] memory debits, JournalEntry[] memory credits) external payable;

    /// @notice Set adapters for a pool in another chain
    /// @param poolId Pool associated to this configuration
    /// @param rivrId Chain where to perform the adapter configuration
    /// @param localAdapters Adapter addresses in this chain
    /// @param remoteAdapters Adapter addresses in the remote chain
    /// @param threshold Minimum number of adapters required to process the messages
    /// @param recoveryIndex Index in adapters array from where consider the adapter as recovery adapter
    /// @param refund Address to receive excess gas refund
    function setAdapters(
        PoolId poolId,
        uint16 rivrId,
        IAdapter[] memory localAdapters,
        bytes32[] memory remoteAdapters,
        uint8 threshold,
        uint8 recoveryIndex,
        address refund
    ) external payable;

    /// @notice Update a gateway manager for a pool
    /// @param poolId Pool associated to this configuration
    /// @param rivrId Chain where to perform the gateway configuration
    /// @param who Address used as manager
    /// @param canManage If enabled as manager
    /// @param refund Address to receive excess gas refund
    function updateGatewayManager(PoolId poolId, uint16 rivrId, bytes32 who, bool canManage, address refund)
        external
        payable;

    /// @notice Update accounting for a holding amount change
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @param isPositive Whether the change is positive
    /// @param diff The amount of change
    function updateAccountingAmount(PoolId poolId, ShareClassId scId, AssetId assetId, bool isPositive, uint128 diff)
        external
        payable;

    /// @notice Update accounting for a holding value change
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @param isPositive Whether the change is positive
    /// @param diff The amount of change
    function updateAccountingValue(PoolId poolId, ShareClassId scId, AssetId assetId, bool isPositive, uint128 diff)
        external
        payable;

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

    /// @notice Helper to construct holding accounts array
    /// @param assetAccount Account for tracking assets
    /// @param equityAccount Account for tracking equity
    /// @param gainAccount Account for tracking gains
    /// @param lossAccount Account for tracking losses
    /// @return accounts Array of holding accounts
    function holdingAccounts(
        AccountId assetAccount,
        AccountId equityAccount,
        AccountId gainAccount,
        AccountId lossAccount
    ) external pure returns (HoldingAccount[] memory accounts);

    /// @notice Helper to construct liability accounts array
    /// @param expenseAccount Account for tracking expenses
    /// @param liabilityAccount Account for tracking liabilities
    /// @return accounts Array of holding accounts
    function liabilityAccounts(AccountId expenseAccount, AccountId liabilityAccount)
        external
        pure
        returns (HoldingAccount[] memory accounts);

    /// @notice Get the price per asset for a holding
    /// @param poolId The pool identifier
    /// @param scId The share class identifier
    /// @param assetId The asset identifier
    /// @return The price in pool units per asset unit
    function pricePoolPerAsset(PoolId poolId, ShareClassId scId, AssetId assetId) external view returns (D18);
}

contracts/core/hub/interfaces/IHubRegistry.sol

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

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

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

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

interface IHubRegistry is IERC6909Decimals {
    //----------------------------------------------------------------------------------------------
    // Events
    //----------------------------------------------------------------------------------------------

    event NewAsset(AssetId indexed assetId, uint8 decimals);
    event NewPool(PoolId poolId, address indexed manager, AssetId indexed currency);
    event UpdateManager(PoolId indexed poolId, address indexed manager, bool canManage);
    event SetMetadata(PoolId indexed poolId, bytes metadata);
    event UpdateDependency(PoolId indexed poolId, bytes32 indexed what, address dependency);
    event UpdateCurrency(PoolId indexed poolId, AssetId currency);
    event SetHubRequestManager(PoolId indexed poolId, uint16 indexed rivrId, IHubRequestManager manager);

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

    error NonExistingPool(PoolId id);
    error AssetAlreadyRegistered();
    error PoolAlreadyRegistered();
    error EmptyAccount();
    error EmptyCurrency();
    error EmptyShareClassManager();
    error AssetNotFound();

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

    /// @notice Register a new asset
    /// @param assetId The asset identifier
    /// @param decimals_ The number of decimals for the asset
    function registerAsset(AssetId assetId, uint8 decimals_) external;

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

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

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

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

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

    /// @notice Updates a dependency of the system
    /// @param poolId The pool identifier
    /// @param what The dependency identifier
    /// @param dependency The dependency contract address
    function updateDependency(PoolId poolId, bytes32 what, address dependency) external;

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

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

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

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

    /// @notice Returns the dependency used in the system
    /// @param poolId The pool identifier
    /// @param what The dependency identifier
    /// @return The dependency contract address
    function dependency(PoolId poolId, bytes32 what) external view returns (address);

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

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

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

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

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

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

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

contracts/core/hub/interfaces/IHubRequestManager.sol

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

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

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

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

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

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

contracts/core/hub/interfaces/IHubRequestManagerCallback.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 IHubRequestManagerCallback {
    /// @notice Handles a request callback originating from a hub request manager.
    /// @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
    /// @param  extraGasLimit Extra gas limit for the callback
    /// @param refund address to refund the excedent of the payment
    function requestCallback(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        bytes calldata payload,
        uint128 extraGasLimit,
        bool unpaidMode,
        address refund
    ) external payable;
}

contracts/core/hub/interfaces/IShareClassManager.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 {ShareClassId} from "../../types/ShareClassId.sol";

struct ShareClassMetadata {
    /// @dev The name of the share class token
    string name;
    /// @dev The symbol of the share class token
    string symbol;
    /// @dev The salt of the share class token
    bytes32 salt;
}

struct Price {
    /// @dev The latest price per share class token
    D18 price;
    /// @dev Timestamp when the price pool per share was computed
    uint64 computedAt;
}

struct IssuancePerNetwork {
    /// @dev Total accumulated amount of shares issued on this network
    uint128 issuances;
    /// @dev Total accumulated amount of shares revoked on this network
    uint128 revocations;
}

interface IShareClassManager {
    //----------------------------------------------------------------------------------------------
    // Events
    //----------------------------------------------------------------------------------------------

    event AddShareClass(
        PoolId indexed poolId, ShareClassId indexed scId, uint32 indexed index, string name, string symbol, bytes32 salt
    );
    event UpdateMetadata(PoolId indexed poolId, ShareClassId indexed scId, string name, string symbol);
    event UpdatePricePoolPerShare(PoolId indexed poolId, ShareClassId indexed scId, D18 price, uint64 computedAt);
    event RemoteIssueShares(
        uint16 indexed rivrId, PoolId indexed poolId, ShareClassId indexed scId, uint128 amount
    );
    event RemoteRevokeShares(
        uint16 indexed rivrId, PoolId indexed poolId, ShareClassId indexed scId, uint128 amount
    );

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

    error InvalidMetadataName();
    error InvalidMetadataSymbol();
    error InvalidSalt();
    error AlreadyUsedSalt();
    error ShareClassNotFound();
    error NegativeIssuance();
    error CannotSetFuturePrice();

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

    /// @notice Update the share class issuance
    /// @param rivrId Identifier of the chain
    /// @param poolId Identifier of the pool
    /// @param scId Identifier of the share class
    /// @param amount The amount to increase or decrease the share class issuance by
    /// @param isIssuance Whether it is an issuance or revocation
    function updateShares(uint16 rivrId, PoolId poolId, ShareClassId scId, uint128 amount, bool isIssuance)
        external;

    /// @notice Adds a new share class to the given pool
    /// @param poolId Identifier of the pool
    /// @param name The name of the share class
    /// @param symbol The symbol of the share class
    /// @param salt The salt used for deploying the share class tokens
    /// @return scId Identifier of the newly added share class
    function addShareClass(PoolId poolId, string calldata name, string calldata symbol, bytes32 salt)
        external
        returns (ShareClassId scId);

    /// @notice Updates the price pool unit per share unit of a share class
    /// @param poolId Identifier of the pool
    /// @param scId Identifier of the share class
    /// @param pricePoolPerShare The price per share of the share class (in the pool currency denomination)
    /// @param computedAt Timestamp when the price was computed (must be <= block.timestamp)
    function updateSharePrice(PoolId poolId, ShareClassId scId, D18 pricePoolPerShare, uint64 computedAt) external;

    /// @notice Updates the metadata of a share class
    /// @param poolId Identifier of the pool
    /// @param scId Identifier of the share class
    /// @param name The name of the share class
    /// @param symbol The symbol of the share class
    function updateMetadata(PoolId poolId, ShareClassId scId, string calldata name, string calldata symbol) external;

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

    /// @notice Returns the number of share classes for the given pool
    /// @param poolId Identifier of the pool in question
    /// @return count Number of share classes for the given pool
    function shareClassCount(PoolId poolId) external view returns (uint32 count);

    /// @notice Checks the existence of a share class
    /// @param poolId Identifier of the pool
    /// @param scId Identifier of the share class
    /// @return Whether the share class exists
    function exists(PoolId poolId, ShareClassId scId) external view returns (bool);

    /// @notice Returns the current price per share and when it was computed
    ///
    /// @param poolId Identifier of the pool
    /// @param scId Identifier of the share class
    /// @return price The latest price per share (in pool currency denomination)
    /// @return computedAt Timestamp when the price was computed (may be earlier than submission time)
    function pricePoolPerShare(PoolId poolId, ShareClassId scId) external view returns (D18 price, uint64 computedAt);

    /// @notice Returns the total issuance across all networks for a share class
    /// @dev     This is only updated when queued shares on the spoke are updated to the hub, so can
    ///                maybe out of sync and not reflect the exact latest issuance across networks.
    ///
    /// @param poolId Identifier of the pool
    /// @param scId Identifier of the share class
    /// @return totalIssuance The total number of shares known to the Hub side
    function totalIssuance(PoolId poolId, ShareClassId scId) external view returns (uint128 totalIssuance);

    /// @notice Exposes issuance of a share class on a given network
    /// @param poolId Identifier of the pool
    /// @param scId Identifier of the share class
    /// @param rivrId Identifier of the chain
    /// @return The share issuance on the specified network
    function issuance(PoolId poolId, ShareClassId scId, uint16 rivrId) external view returns (uint128);

    /// @notice Returns the combined issuance (issuances and revocations) for a share class on a given network
    /// @param poolId Identifier of the pool
    /// @param scId Identifier of the share class
    /// @param rivrId Identifier of the chain
    /// @return issuances The total accumulated amount of shares issued on this network
    /// @return revocations The total accumulated amount of shares revoked on this network
    function issuancePerNetwork(PoolId poolId, ShareClassId scId, uint16 rivrId)
        external
        view
        returns (uint128 issuances, uint128 revocations);

    /// @notice Determines the next share class id for the given pool
    /// @param poolId Identifier of the pool
    /// @return scId Identifier of the next share class
    function previewNextShareClassId(PoolId poolId) external view returns (ShareClassId scId);

    /// @notice Determines the share class id for the given pool and index
    /// @param poolId Identifier of the pool
    /// @param index The pool-internal index of the share class id
    /// @return scId Identifier of the underlying share class
    function previewShareClassId(PoolId poolId, uint32 index) external pure returns (ShareClassId scId);

    /// @notice Returns the metadata of the share class
    /// @param poolId Identifier of the pool
    /// @param scId Identifier of the share class
    /// @return name The registered name of the share class token
    /// @return symbol The registered symbol of the share class token
    /// @return salt The registered salt of the share class token, used for deterministic deployments
    function metadata(PoolId poolId, ShareClassId scId)
        external
        view
        returns (string memory name, string memory symbol, bytes32 salt);
}

contracts/core/hub/interfaces/ISnapshotHook.sol

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

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

/// @notice Hook interface that is called whenever the accounting system of the Hub, for a given share token on
///         1 network, as in a (poolId, scId, rivrId) tuple, is in a synchronous state. This means the assets
///         (deposits/withdrawals of holdings) are updated in alignment with the issuance of shares.
///
///         This can be used to compute higher-level properties such as the NAV and NAV/share, which require
///         assets and shares to be in sync to be accurate.
///
///         NOTE: Only the state for the given rivrId is guaranteed to be in sync. This means, if
///         the snapshot hook reads state from the accounting layer, the accounts of holdings and liabilities
///         should be set up per network, to not mingle in sync and out of sync state.
interface ISnapshotHook {
    /// @notice Callback when there is a sync snapshot.
    function onSync(PoolId poolId, ShareClassId scId, uint16 rivrId) external;

    /// @notice Callback when there is a cross-chain transfer leading to issuance updates
    function onTransfer(
        PoolId poolId,
        ShareClassId scId,
        uint16 fromRIVRId,
        uint16 toRIVRId,
        uint128 sharesTransferred
    ) external;
}

contracts/core/hub/interfaces/IValuation.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";

/// Interface for valuation of assets, denominated in the pool currency.
interface IValuation {
    /// @notice Returns the price as a fixed point number with 18 decimals.
    function getPrice(PoolId poolId, ShareClassId scId, AssetId assetId) external view returns (D18);

    /// @notice Returns the value of baseAmount of base in quote terms, e.g. 10 ETH (base) in USDC (quote).
    /// @param assetId The asset in which the baseAmount is denominated in
    /// @param baseAmount The amount of base in base terms.
    function getQuote(PoolId poolId, ShareClassId scId, AssetId assetId, uint128 baseAmount)
        external
        view
        returns (uint128 quoteAmount);
}

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

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

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

type AccountId is uint256;

function raw(AccountId accountId_) pure returns (uint256) {
    return AccountId.unwrap(accountId_);
}

function neq(AccountId a, AccountId b) pure returns (bool) {
    return AccountId.unwrap(a) != AccountId.unwrap(b);
}

function isNull(AccountId accountId) pure returns (bool) {
    return AccountId.unwrap(accountId) == 0;
}

function withRIVRId(uint16 rivrId, uint16 index) pure returns (AccountId) {
    return AccountId.wrap((uint256(rivrId) << 16) | uint256(index));
}

function withAssetId(AssetId assetId, uint16 index) pure returns (AccountId) {
    return AccountId.wrap((uint256(assetId.raw()) << 16) | uint256(index));
}

using {raw, neq as !=, isNull} for AccountId global;

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/core/utils/BatchedMulticall.sol

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

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

import {Multicall, IMulticall} from "../../misc/Multicall.sol";

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

/// @title  BatchedMulticall
/// @notice Abstract contract that extends Multicall with gateway batching support, enabling efficient
///         aggregation of multiple cross-chain messages into a single batch to reduce transaction costs
///         while coordinating payment handling across batched operations.
/// @dev    IMPORTANT: Integrators MUST replace msg.sender with msgSender() and msg.value with msgValue()
///         for the methods called by the multicall.
/// @dev    IMPORTANT: The contract which extends BatchedMulticall must not treat the gateway
///         as a permissioned/authenticated msg.sender to avoid the multicall execution to call auth methods,
///         opening security issues.
abstract contract BatchedMulticall is Multicall, IBatchedMulticall {
    IGateway public gateway;
    address private transient _sender;

    constructor(IGateway gateway_) {
        gateway = gateway_;
    }

    /// @inheritdoc IMulticall
    /// @notice     With extra support for batching
    function multicall(bytes[] calldata data) public payable override {
        require(_sender == address(0), AlreadyBatching());

        _sender = msg.sender;
        gateway.withBatch{value: msg.value}(
            abi.encodeWithSelector(BatchedMulticall.executeMulticall.selector, data), msg.sender
        );
        _sender = address(0);
    }

    function executeMulticall(bytes[] calldata data) external payable protected {
        gateway.lockCallback();
        super.multicall(data);
    }

    /// @dev Integrators MUST use msgSender() instead of msg.sender, since this is replaced
    ///      by the gateway address inside the multicall.
    function msgSender() internal view virtual returns (address) {
        return _sender != address(0) && msg.sender == address(gateway) ? _sender : msg.sender;
    }

    /// @dev Only the call to multicall should pass the msg.value, which is then passed
    ///      in `gateway.withBatch`. No inner calls should pass any msg.value.
    function msgValue() internal view returns (uint256 value) {
        return _sender != address(0) ? 0 : msg.value;
    }
}

contracts/core/utils/interfaces/IBatchedMulticall.sol

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

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

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

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

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

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

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

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

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

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

contracts/misc/Recoverable.sol

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

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

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

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

contracts/misc/ReentrancyProtection.sol

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

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

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

    address private transient _initiator;

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

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

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

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

contracts/misc/interfaces/IERC20.sol

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

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

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

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

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

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

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

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

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

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

contracts/misc/interfaces/IERC6909.sol

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

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

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

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

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

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

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

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

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

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

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

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

    error EmptyURI();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /// @notice             Enforces a transfer from `spender` point of view.
    ///
    ///
    /// @param sender       The owner of the `tokenId`
    /// @param receiver     Address of the receiving party
    /// @param tokenId      Token Id
    /// @param amount       Amount to be transferred
    function authTransferFrom(address sender, address receiver, uint256 tokenId, uint256 amount) external returns (bool);
}

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

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

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

contracts/misc/interfaces/IERC7751.sol

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

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

contracts/misc/interfaces/IMulticall.sol

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

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

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

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/libraries/SafeTransferLib.sol

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

import {IERC20} from "../interfaces/IERC20.sol";
import {IERC7751} from "../interfaces/IERC7751.sol";

/// @title  Safe Transfer Lib
/// @author Modified from Uniswap v3 Periphery (libraries/TransferHelper.sol)
library SafeTransferLib {
    error NoCode();
    error SafeTransferFromFailed();
    error SafeTransferFailed();
    error SafeApproveFailed();
    error SafeTransferEthFailed();

    /// @notice Transfers tokens from the targeted address to the given destination
    /// @notice Errors if transfer fails
    /// @param token The contract address of the token to be transferred
    /// @param from The originating address from which the tokens will be transferred
    /// @param to The destination address of the transfer
    /// @param value The amount to be transferred
    function safeTransferFrom(address token, address from, address to, uint256 value) internal {
        require(address(token).code.length > 0, NoCode());

        (bool success, bytes memory returnData) = token.call(abi.encodeCall(IERC20.transferFrom, (from, to, value)));
        require(
            success && (returnData.length == 0 || abi.decode(returnData, (bool))),
            IERC7751.WrappedError(
                token, IERC20.transferFrom.selector, returnData, abi.encodeWithSelector(SafeTransferFromFailed.selector)
            )
        );
    }

    /// @notice Transfers tokens from msg.sender to a recipient
    /// @dev Errors if transfer fails
    /// @param token The contract address of the token which will be transferred
    /// @param to The recipient of the transfer
    /// @param value The value of the transfer
    function safeTransfer(address token, address to, uint256 value) internal {
        require(address(token).code.length > 0, NoCode());

        (bool success, bytes memory returnData) = token.call(abi.encodeCall(IERC20.transfer, (to, value)));
        require(
            success && (returnData.length == 0 || abi.decode(returnData, (bool))),
            IERC7751.WrappedError(
                token, IERC20.transfer.selector, returnData, abi.encodeWithSelector(SafeTransferFailed.selector)
            )
        );
    }

    /// @notice Approves the stipulated contract to spend the given allowance in the given token
    /// @dev Errors if approval fails
    /// @param token The contract address of the token to be approved
    /// @param to The target of the approval
    /// @param value The amount of the given token the target will be allowed to spend
    function safeApprove(address token, address to, uint256 value) internal {
        require(address(token).code.length > 0, NoCode());

        (bool success, bytes memory returnData) = token.call(abi.encodeCall(IERC20.approve, (to, value)));
        require(
            success && (returnData.length == 0 || abi.decode(returnData, (bool))),
            IERC7751.WrappedError(
                token, IERC20.approve.selector, returnData, abi.encodeWithSelector(SafeApproveFailed.selector)
            )
        );
    }

    /// @notice Transfers ETH to the recipient address
    /// @dev Fails with `STE`
    /// @dev Make sure that method that is using this function is protected from reentrancy
    /// @param to The destination of the transfer
    /// @param value The value to be transferred
    function safeTransferETH(address to, uint256 value) internal {
        (bool success,) = to.call{value: value}(new bytes(0));
        require(success, SafeTransferEthFailed());
    }
}

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;

contracts/vaults/libraries/RequestCallbackMessageLib.sol

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

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

enum RequestCallbackType {
    /// @dev Placeholder for null request callback type
    Invalid,
    ApprovedDeposits,
    IssuedShares,
    RevokedShares,
    FulfilledDepositRequest,
    FulfilledRedeemRequest
}

library RequestCallbackMessageLib {
    using RequestCallbackMessageLib for bytes;
    using BytesLib for bytes;
    using CastLib for *;

    error UnknownRequestCallbackType();

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

    //---------------------------------------
    //    RequestCallback.ApprovedDeposits (submsg)
    //---------------------------------------

    struct ApprovedDeposits {
        uint128 assetAmount;
        uint128 pricePoolPerAsset;
    }

    function deserializeApprovedDeposits(bytes memory data) internal pure returns (ApprovedDeposits memory) {
        require(requestCallbackType(data) == RequestCallbackType.ApprovedDeposits, UnknownRequestCallbackType());

        return ApprovedDeposits({assetAmount: data.toUint128(1), pricePoolPerAsset: data.toUint128(17)});
    }

    function serialize(ApprovedDeposits memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(RequestCallbackType.ApprovedDeposits, t.assetAmount, t.pricePoolPerAsset);
    }

    //---------------------------------------
    //    RequestCallback.IssuedShares (submsg)
    //---------------------------------------

    struct IssuedShares {
        uint128 shareAmount;
        uint128 pricePoolPerShare;
    }

    function deserializeIssuedShares(bytes memory data) internal pure returns (IssuedShares memory) {
        require(requestCallbackType(data) == RequestCallbackType.IssuedShares, UnknownRequestCallbackType());

        return IssuedShares({shareAmount: data.toUint128(1), pricePoolPerShare: data.toUint128(17)});
    }

    function serialize(IssuedShares memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(RequestCallbackType.IssuedShares, t.shareAmount, t.pricePoolPerShare);
    }

    //---------------------------------------
    //    RequestCallback.RevokedShares (submsg)
    //---------------------------------------

    struct RevokedShares {
        uint128 assetAmount;
        uint128 shareAmount;
        uint128 pricePoolPerShare;
    }

    function deserializeRevokedShares(bytes memory data) internal pure returns (RevokedShares memory) {
        require(requestCallbackType(data) == RequestCallbackType.RevokedShares, UnknownRequestCallbackType());

        return RevokedShares({
            assetAmount: data.toUint128(1), shareAmount: data.toUint128(17), pricePoolPerShare: data.toUint128(33)
        });
    }

    function serialize(RevokedShares memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(RequestCallbackType.RevokedShares, t.assetAmount, t.shareAmount, t.pricePoolPerShare);
    }

    //---------------------------------------
    //    RequestCallback.FulfilledDepositRequest (submsg)
    //---------------------------------------

    struct FulfilledDepositRequest {
        bytes32 investor;
        uint128 fulfilledAssetAmount;
        uint128 fulfilledShareAmount;
        uint128 cancelledAssetAmount;
    }

    function deserializeFulfilledDepositRequest(bytes memory data)
        internal
        pure
        returns (FulfilledDepositRequest memory)
    {
        require(requestCallbackType(data) == RequestCallbackType.FulfilledDepositRequest, UnknownRequestCallbackType());
        return FulfilledDepositRequest({
            investor: data.toBytes32(1),
            fulfilledAssetAmount: data.toUint128(33),
            fulfilledShareAmount: data.toUint128(49),
            cancelledAssetAmount: data.toUint128(65)
        });
    }

    function serialize(FulfilledDepositRequest memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(
            RequestCallbackType.FulfilledDepositRequest,
            t.investor,
            t.fulfilledAssetAmount,
            t.fulfilledShareAmount,
            t.cancelledAssetAmount
        );
    }

    //---------------------------------------
    //    RequestCallback.FulfilledRedeemRequest (submsg)
    //---------------------------------------

    struct FulfilledRedeemRequest {
        bytes32 investor;
        uint128 fulfilledAssetAmount;
        uint128 fulfilledShareAmount;
        uint128 cancelledShareAmount;
    }

    function deserializeFulfilledRedeemRequest(bytes memory data)
        internal
        pure
        returns (FulfilledRedeemRequest memory)
    {
        require(requestCallbackType(data) == RequestCallbackType.FulfilledRedeemRequest, UnknownRequestCallbackType());
        return FulfilledRedeemRequest({
            investor: data.toBytes32(1),
            fulfilledAssetAmount: data.toUint128(33),
            fulfilledShareAmount: data.toUint128(49),
            cancelledShareAmount: data.toUint128(65)
        });
    }

    function serialize(FulfilledRedeemRequest memory t) internal pure returns (bytes memory) {
        return abi.encodePacked(
            RequestCallbackType.FulfilledRedeemRequest,
            t.investor,
            t.fulfilledAssetAmount,
            t.fulfilledShareAmount,
            t.cancelledShareAmount
        );
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.