Skip to content
Verified contractExactISC

Holdings

Address0xfc8470f98a91be3cfe53a91db1e4bec87de1ea0c
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.36

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.36+commit.8a079791
Language
solidity
Optimization
No
License
ISC
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,427,153
Creation transaction
0xff02baf5be…31d0fa533f

contracts/hub/Holdings.sol

// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;

import {Auth} from "contracts/misc/Auth.sol";
import {D18} from "contracts/misc/types/D18.sol";
import {MathLib} from "contracts/misc/libraries/MathLib.sol";

import {PoolId} from "contracts/common/types/PoolId.sol";
import {AssetId} from "contracts/common/types/AssetId.sol";
import {AccountId} from "contracts/common/types/AccountId.sol";
import {PricingLib} from "contracts/common/libraries/PricingLib.sol";
import {ShareClassId} from "contracts/common/types/ShareClassId.sol";
import {IValuation} from "contracts/common/interfaces/IValuation.sol";
import {ISnapshotHook} from "contracts/common/interfaces/ISnapshotHook.sol";

import {IHubRegistry} from "contracts/hub/interfaces/IHubRegistry.sol";
import {IHoldings, Holding, HoldingAccount, Snapshot} from "contracts/hub/interfaces/IHoldings.sol";

/// @title  Holdings
/// @notice Bookkeeping of the holdings and its associated accounting IDs for each pool.
/// @dev    Keeps track of whether the current holdings + share issuance in `ShareClassManager` is a snapshot. This is
///         the case when assets and shares are in sync for the given network, and can be used to derive computations
///         that rely on the ratio, such as the price per share.
contract Holdings is Auth, IHoldings {
    using MathLib for uint256;

    IHubRegistry public immutable hubRegistry;

    mapping(PoolId => ISnapshotHook) public snapshotHook;
    mapping(PoolId => mapping(ShareClassId => mapping(AssetId => Holding))) public holding;
    mapping(PoolId => mapping(ShareClassId => mapping(uint16 tokenId => Snapshot))) public snapshot;
    mapping(PoolId => mapping(ShareClassId => mapping(AssetId => mapping(uint8 kind => AccountId)))) public accountId;

    constructor(IHubRegistry hubRegistry_, address deployer) Auth(deployer) {
        hubRegistry = hubRegistry_;
    }

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

    /// @inheritdoc IHoldings
    function initialize(
        PoolId poolId,
        ShareClassId scId,
        AssetId assetId,
        IValuation valuation_,
        bool isLiability_,
        HoldingAccount[] memory accounts
    ) external auth {
        require(!scId.isNull(), WrongShareClassId());
        require(address(valuation_) != address(0), WrongValuation());

        Holding storage holding_ = holding[poolId][scId][assetId];
        require(address(holding_.valuation) == address(0), AlreadyInitialized());

        holding_.valuation = valuation_;
        holding_.isLiability = isLiability_;

        for (uint256 i; i < accounts.length; i++) {
            accountId[poolId][scId][assetId][accounts[i].kind] = accounts[i].accountId;
        }

        emit Initialize(poolId, scId, assetId, valuation_, isLiability_, accounts);
    }

    /// @inheritdoc IHoldings
    function setAccountId(PoolId poolId, ShareClassId scId, AssetId assetId, uint8 kind, AccountId accountId_)
        external
        auth
    {
        Holding storage holding_ = holding[poolId][scId][assetId];
        require(address(holding_.valuation) != address(0), HoldingNotFound());

        accountId[poolId][scId][assetId][kind] = accountId_;

        emit SetAccountId(poolId, scId, assetId, kind, accountId_);
    }

    /// @inheritdoc IHoldings
    function updateValuation(PoolId poolId, ShareClassId scId, AssetId assetId, IValuation valuation_) external auth {
        require(address(valuation_) != address(0), WrongValuation());

        Holding storage holding_ = holding[poolId][scId][assetId];
        require(address(holding_.valuation) != address(0), HoldingNotFound());

        holding_.valuation = valuation_;

        emit UpdateValuation(poolId, scId, assetId, valuation_);
    }

    /// @inheritdoc IHoldings
    function updateIsLiability(PoolId poolId, ShareClassId scId, AssetId assetId, bool isLiability_) external auth {
        Holding storage holding_ = holding[poolId][scId][assetId];
        require(address(holding_.valuation) != address(0), HoldingNotFound());
        require(holding_.assetAmount == 0 && holding_.assetAmountValue == 0, HoldingNotZero());

        holding_.isLiability = isLiability_;

        emit UpdateIsLiability(poolId, scId, assetId, isLiability_);
    }

    /// @inheritdoc IHoldings
    function setSnapshotHook(PoolId poolId, ISnapshotHook hook) external auth {
        snapshotHook[poolId] = hook;

        emit SetSnapshotHook(poolId, hook);
    }

    /// @inheritdoc IHoldings
    function setSnapshot(PoolId poolId, ShareClassId scId, uint16 tokenId, bool isSnapshot, uint64 nonce)
        external
        auth
    {
        Snapshot storage snapshot_ = snapshot[poolId][scId][tokenId];
        require(snapshot_.nonce == nonce, InvalidNonce(snapshot_.nonce, nonce));

        snapshot_.isSnapshot = isSnapshot;
        snapshot_.nonce++;

        emit SetSnapshot(poolId, scId, tokenId, isSnapshot, nonce);

        if (!isSnapshot) return;

        ISnapshotHook hook = snapshotHook[poolId];
        if (address(hook) != address(0)) hook.onSync(poolId, scId, tokenId);
    }

    //----------------------------------------------------------------------------------------------
    // Value updates
    //----------------------------------------------------------------------------------------------

    /// @inheritdoc IHoldings
    function increase(PoolId poolId, ShareClassId scId, AssetId assetId, D18 pricePoolPerAsset, uint128 amount_)
        external
        auth
        returns (uint128 amountValue)
    {
        Holding storage holding_ = holding[poolId][scId][assetId];

        amountValue = PricingLib.convertWithPrice(
            amount_, hubRegistry.decimals(assetId), hubRegistry.decimals(poolId), pricePoolPerAsset
        );

        holding_.assetAmount += amount_;
        holding_.assetAmountValue += amountValue;

        emit Increase(poolId, scId, assetId, pricePoolPerAsset, amount_, amountValue);
    }

    /// @inheritdoc IHoldings
    function decrease(PoolId poolId, ShareClassId scId, AssetId assetId, D18 pricePoolPerAsset, uint128 amount_)
        external
        auth
        returns (uint128 amountValue)
    {
        Holding storage holding_ = holding[poolId][scId][assetId];

        amountValue = PricingLib.convertWithPrice(
            amount_, hubRegistry.decimals(assetId), hubRegistry.decimals(poolId), pricePoolPerAsset
        );

        holding_.assetAmount -= amount_;
        holding_.assetAmountValue -= amountValue;

        emit Decrease(poolId, scId, assetId, pricePoolPerAsset, amount_, amountValue);
    }

    /// @inheritdoc IHoldings
    function update(PoolId poolId, ShareClassId scId, AssetId assetId)
        external
        auth
        returns (bool isPositive, uint128 diffValue)
    {
        Holding storage holding_ = holding[poolId][scId][assetId];
        require(address(holding_.valuation) != address(0), HoldingNotFound());

        uint128 currentAmountValue =
            holding_.valuation.getQuote(holding_.assetAmount, assetId, hubRegistry.currency(poolId));

        isPositive = currentAmountValue >= holding_.assetAmountValue;
        diffValue =
            isPositive ? currentAmountValue - holding_.assetAmountValue : holding_.assetAmountValue - currentAmountValue;

        holding_.assetAmountValue = currentAmountValue;

        emit Update(poolId, scId, assetId, isPositive, diffValue);
    }

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

    /// @inheritdoc IHoldings
    function isInitialized(PoolId poolId, ShareClassId scId, AssetId assetId) external view returns (bool) {
        return address(holding[poolId][scId][assetId].valuation) != address(0);
    }

    /// @inheritdoc IHoldings
    function value(PoolId poolId, ShareClassId scId, AssetId assetId) external view returns (uint128 value_) {
        Holding storage holding_ = holding[poolId][scId][assetId];
        return holding_.assetAmountValue;
    }

    /// @inheritdoc IHoldings
    function amount(PoolId poolId, ShareClassId scId, AssetId assetId) external view returns (uint128 amount_) {
        Holding storage holding_ = holding[poolId][scId][assetId];
        return holding_.assetAmount;
    }

    /// @inheritdoc IHoldings
    function valuation(PoolId poolId, ShareClassId scId, AssetId assetId) external view returns (IValuation) {
        Holding storage holding_ = holding[poolId][scId][assetId];
        require(address(holding_.valuation) != address(0), HoldingNotFound());

        return holding_.valuation;
    }

    /// @inheritdoc IHoldings
    function isLiability(PoolId poolId, ShareClassId scId, AssetId assetId) external view returns (bool) {
        Holding storage holding_ = holding[poolId][scId][assetId];
        require(address(holding_.valuation) != address(0), HoldingNotFound());

        return holding_.isLiability;
    }
}

contracts/common/interfaces/ISnapshotHook.sol

// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;

import {PoolId} from "contracts/common/types/PoolId.sol";
import {ShareClassId} from "contracts/common/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, tokenId) tuple, is in a synchronous state. This means the assets
///         (deposits/withdrawals of holdings) are updated in aligment 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 tokenId 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 tokenId) external;
}

contracts/common/interfaces/IValuation.sol

// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;

import {AssetId} from "contracts/common/types/AssetId.sol";

/// Based on [ERC-7726](https://eips.ethereum.org/EIPS/eip-7726): Common Quote Oracle, but adapted for ERC6909.
/// Interface for asset conversions.
interface IValuation {
    /// @notice Returns the value of baseAmount of base in quote terms, e.g. 10 ETH (base) in USDC (quote).
    /// @param base The asset in which the baseAmount is denominated in
    /// @param quote The asset in which the user needs to value the baseAmount
    /// @param baseAmount The amount of base in base terms.
    function getQuote(uint128 baseAmount, AssetId base, AssetId quote) external view returns (uint128 quoteAmount);
}

contracts/common/libraries/PricingLib.sol

// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;

import {D18, d18} from "contracts/misc/types/D18.sol";
import {MathLib} from "contracts/misc/libraries/MathLib.sol";
import {IERC20Metadata} from "contracts/misc/interfaces/IERC20.sol";
import {IERC6909MetadataExt} from "contracts/misc/interfaces/IERC6909.sol";

import {PricingLib} from "contracts/common/libraries/PricingLib.sol";

library PricingLib {
    using MathLib for *;

    /// @dev Prices are fixed-point integers with 18 decimals
    uint8 internal constant PRICE_DECIMALS = 18;

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

    /// @dev Converts the given asset amount to share amount. Returned value is in share decimals.
    /// @dev Assumes handling of zero denominator price (priceAssetPerShare_) by consumer.
    ///
    ///      NOTE: MUST ONLY be used in AsyncRequestManager which rely on priceAssetPerShare that is derived from
    ///      Fulfilled* message amounts. Any other codepath must use the variant with pricePoolPerAsset
    ///      and pricePoolPerShare
    function assetToShareAmount(
        address shareToken,
        address asset,
        uint256 tokenId,
        uint128 assetAmount,
        D18 priceAssetPerShare_,
        MathLib.Rounding rounding
    ) internal view returns (uint128 shares) {
        if (assetAmount == 0) {
            return 0;
        }

        uint8 assetDecimals = _getAssetDecimals(asset, tokenId);
        uint8 shareDecimals = IERC20Metadata(shareToken).decimals();

        return PricingLib.convertWithReciprocalPrice(
            assetAmount, assetDecimals, shareDecimals, priceAssetPerShare_, rounding
        ).toUint128();
    }

    /// @dev Converts the given asset amount to share amount. Returned value is in share decimals.
    /// @dev Assumes handling of zero denominator price (pricePoolPerShare) by consumer.
    function assetToShareAmount(
        address shareToken,
        address asset,
        uint256 tokenId,
        uint128 assetAmount,
        D18 pricePoolPerAsset,
        D18 pricePoolPerShare,
        MathLib.Rounding rounding
    ) internal view returns (uint128 shares) {
        if (assetAmount == 0 || pricePoolPerAsset.isZero()) {
            return 0;
        }

        uint8 assetDecimals = _getAssetDecimals(asset, tokenId);
        uint8 shareDecimals = IERC20Metadata(shareToken).decimals();

        return PricingLib.assetToShareAmount(
            assetAmount, assetDecimals, shareDecimals, pricePoolPerAsset, pricePoolPerShare, rounding
        ).toUint128();
    }

    /// @dev Converts the given share amount to asset amount. Returned value is in share decimals.
    ///
    ///      NOTE: MUST ONLY be used in AsyncRequestManager which rely on priceAssetPerShare that is derived from
    ///      Fulfilled*  message amounts. Any other codepath must use the variant with pricePoolPerAsset and
    ///      pricePoolPerShare
    function shareToAssetAmount(
        address shareToken,
        uint128 shareAmount,
        address asset,
        uint256 tokenId,
        D18 priceAssetPerShare_,
        MathLib.Rounding rounding
    ) internal view returns (uint128 assets) {
        if (shareAmount == 0 || priceAssetPerShare_.isZero()) {
            return 0;
        }

        uint8 assetDecimals = _getAssetDecimals(asset, tokenId);
        uint8 shareDecimals = IERC20Metadata(shareToken).decimals();

        return PricingLib.convertWithPrice(shareAmount, shareDecimals, assetDecimals, priceAssetPerShare_, rounding);
    }

    /// @dev Converts the given share amount to asset amount. Returned value is in share decimals.
    /// @dev Assumes handling of zero denominator price (pricePoolPerAsset) by consumer.
    function shareToAssetAmount(
        address shareToken,
        uint128 shareAmount,
        address asset,
        uint256 tokenId,
        D18 pricePoolPerShare,
        D18 pricePoolPerAsset,
        MathLib.Rounding rounding
    ) internal view returns (uint128 shares) {
        if (shareAmount == 0 || pricePoolPerShare.isZero()) {
            return 0;
        }

        uint8 assetDecimals = _getAssetDecimals(asset, tokenId);
        uint8 shareDecimals = IERC20Metadata(shareToken).decimals();

        // NOTE: Pool and share denomination are always equal by design
        return PricingLib.shareToAssetAmount(
            shareAmount, shareDecimals, assetDecimals, pricePoolPerShare, pricePoolPerAsset, rounding
        ).toUint128();
    }

    /// @dev Calculates the asset price per share returns the value in price decimals
    ///      Denominated in ASSET_UNIT/SHARE_UNIT
    /// @dev Assumes handling of zero denominator (shares == 0) by consumer.
    function calculatePriceAssetPerShare(
        address shareToken,
        uint128 shares,
        address asset,
        uint256 tokenId,
        uint128 assets,
        MathLib.Rounding rounding
    ) internal view returns (D18 priceAssetPerShare_) {
        if (assets == 0) {
            return d18(0);
        }

        uint8 assetDecimals = _getAssetDecimals(asset, tokenId);
        uint8 shareDecimals = IERC20Metadata(shareToken).decimals();

        // NOTE: More precise than utilizing D18
        return d18(
            _toPriceDecimals(assets, assetDecimals).mulDiv(
                10 ** PRICE_DECIMALS, _toPriceDecimals(shares, shareDecimals), rounding
            ).toUint128()
        );
    }

    //----------------------------------------------------------------------------------------------
    // Pure methods
    //----------------------------------------------------------------------------------------------

    /// @dev Converts an amount using decimals and price with implicit rounding down
    function convertWithPrice(uint256 baseAmount, uint8 baseDecimals, uint8 quoteDecimals, D18 priceQuotePerBase)
        internal
        pure
        returns (uint128 quoteAmount)
    {
        return convertWithPrice(baseAmount, baseDecimals, quoteDecimals, priceQuotePerBase, MathLib.Rounding.Down);
    }

    /// @dev Converts an amount using decimals and price with explicit rounding.
    function convertWithPrice(
        uint256 baseAmount,
        uint8 baseDecimals,
        uint8 quoteDecimals,
        D18 priceQuotePerBase,
        MathLib.Rounding rounding
    ) internal pure returns (uint128 quoteAmount) {
        if (baseDecimals == quoteDecimals) {
            return priceQuotePerBase.mulUint256(baseAmount, rounding).toUint128();
        }

        return MathLib.mulDiv(
            priceQuotePerBase.raw(), baseAmount * 10 ** quoteDecimals, 10 ** (baseDecimals + PRICE_DECIMALS), rounding
        ) // cancel out exponentiation from D18 multiplication
            .toUint128();
    }

    /// @dev Converts an amount using decimals and reciprocal price.
    /// @dev Assumes handling of zero denominator price (priceBasePerQuote) by consumer.
    ///
    ///      NOTE: More precise than convertWithPrice(,,,price.reciprocal,)
    function convertWithReciprocalPrice(
        uint256 baseAmount,
        uint8 baseDecimals,
        uint8 quoteDecimals,
        D18 priceBasePerQuote,
        MathLib.Rounding rounding
    ) internal pure returns (uint128 quoteAmount) {
        require(priceBasePerQuote.isNotZero(), "PricingLib/division-by-zero");

        if (baseDecimals == quoteDecimals) {
            return priceBasePerQuote.reciprocalMulUint256(baseAmount, rounding).toUint128();
        }

        return MathLib.mulDiv(
            10 ** quoteDecimals * baseAmount,
            10 ** PRICE_DECIMALS,
            10 ** baseDecimals * priceBasePerQuote.raw(),
            rounding
        ).toUint128();
    }

    /// @dev Converts an amount using decimals and two prices.
    /// @dev Assumes handling of zero denominator price (priceDenominator) by consumer.
    ///
    ///      NOTE: More precise than custom math with one price and convertWith{Reciprocal}Price for the other
    function convertWithPrices(
        uint256 baseAmount,
        uint8 baseDecimals,
        uint8 quoteDecimals,
        D18 priceNumerator,
        D18 priceDenominator,
        MathLib.Rounding rounding
    ) internal pure returns (uint128 quoteAmount) {
        require(priceDenominator.isNotZero(), "PricingLib/division-by-zero");

        return MathLib.mulDiv(
            priceNumerator.raw(),
            10 ** quoteDecimals * baseAmount,
            10 ** baseDecimals * priceDenominator.raw(),
            rounding
        ).toUint128();
    }

    /// @dev Converts asset amount to share amount.
    /// @dev Assumes handling of zero denominator price (pricePoolPerShare) by consumer.
    ///
    ///      NOTE: Pool and share denomination are always equal by design
    function assetToShareAmount(
        uint256 assetAmount,
        uint8 assetDecimals,
        uint8 shareDecimals,
        D18 pricePoolPerAsset,
        D18 pricePoolPerShare,
        MathLib.Rounding rounding
    ) internal pure returns (uint128 shareAmount) {
        return
            convertWithPrices(assetAmount, assetDecimals, shareDecimals, pricePoolPerAsset, pricePoolPerShare, rounding);
    }

    /// @dev Converts share amount to asset asset amount.
    /// @dev Assumes handling of zero denominator price (pricePoolPerAsset) by consumer.
    ///
    ///      NOTE: Pool and share denomination are always equal by design
    function shareToAssetAmount(
        uint256 shareAmount,
        uint8 shareDecimals,
        uint8 assetDecimals,
        D18 pricePoolPerShare,
        D18 pricePoolPerAsset,
        MathLib.Rounding rounding
    ) internal pure returns (uint128 assetAmount) {
        return
            convertWithPrices(shareAmount, shareDecimals, assetDecimals, pricePoolPerShare, pricePoolPerAsset, rounding);
    }

    /// @dev Converts pool amount to asset amount.
    /// @dev Assumes handling of zero denominator price (pricePoolPerAsset) by consumer.
    function poolToAssetAmount(
        uint256 poolAmount,
        uint8 poolDecimals,
        uint8 assetDecimals,
        D18 pricePoolPerAsset,
        MathLib.Rounding rounding
    ) internal pure returns (uint128 assetAmount) {
        return convertWithReciprocalPrice(poolAmount, poolDecimals, assetDecimals, pricePoolPerAsset, rounding);
    }

    /// @dev Converts asset amount to pool amount.
    function assetToPoolAmount(
        uint128 assetAmount,
        uint8 assetDecimals,
        uint8 poolDecimals,
        D18 pricePoolPerAsset,
        MathLib.Rounding rounding
    ) internal pure returns (uint128 poolAmount) {
        return convertWithPrice(assetAmount, assetDecimals, poolDecimals, pricePoolPerAsset, rounding);
    }

    /// @dev Returns the asset price per share denominated in ASSET_UNIT/SHARE_UNIT
    /// @dev Assumes handling of zero denominator price (pricePoolPerAsset) by consumer.
    ///
    ///      NOTE: Should never be used for calculating amounts due to precision loss. Instead, please refer to
    ///      conversion relying on pricePoolPerShare and pricePoolPerAsset.
    function priceAssetPerShare(D18 pricePoolPerShare, D18 pricePoolPerAsset)
        internal
        pure
        returns (D18 priceAssetPerShare_)
    {
        return pricePoolPerShare / pricePoolPerAsset;
    }

    //----------------------------------------------------------------------------------------------
    // Private methods
    //----------------------------------------------------------------------------------------------

    /// @dev Returns the asset decimals
    function _getAssetDecimals(address asset, uint256 tokenId) private view returns (uint8 assetDecimals) {
        return tokenId == 0 ? IERC20Metadata(asset).decimals() : IERC6909MetadataExt(asset).decimals(tokenId);
    }

    /// @dev When converting assets to shares using the price, all values are normalized to PRICE_DECIMALS
    ///      NOTE: We require all assets to have 2 <= decimals <= 18, see `Spoke.registerAsset`
    function _toPriceDecimals(uint128 _value, uint8 decimals) private pure returns (uint256) {
        if (PRICE_DECIMALS == decimals) return uint256(_value);
        return uint256(_value) * 10 ** (PRICE_DECIMALS - decimals);
    }
}

contracts/common/types/AccountId.sol

// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;

type AccountId is uint32;

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

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

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

contracts/common/types/AssetId.sol

// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;

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

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

contracts/common/types/PoolId.sol

// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;

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

using MathLib for uint256;

type PoolId is uint64;

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

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

contracts/common/types/ShareClassId.sol

// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;

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

type ShareClassId is bytes16;

function isNull(ShareClassId scId) pure returns (bool) {
    return ShareClassId.unwrap(scId) == 0;
}

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, raw, equals as ==} for ShareClassId global;

contracts/hub/interfaces/IHoldings.sol

// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;

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

import {PoolId} from "contracts/common/types/PoolId.sol";
import {AssetId} from "contracts/common/types/AssetId.sol";
import {AccountId} from "contracts/common/types/AccountId.sol";
import {ShareClassId} from "contracts/common/types/ShareClassId.sol";
import {IValuation} from "contracts/common/interfaces/IValuation.sol";
import {ISnapshotHook} from "contracts/common/interfaces/ISnapshotHook.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 {
    /// @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 tokenId, bool isSnapshot, uint64 nonce
    );

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

    /// @notice Initializes a new holding in a pool using a valuation
    /// @dev    `increase()` and `decrease()` can be called before 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.
    /// @return value The value the holding has increment.
    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.
    /// @return value The value the holding has decrement.
    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.
    /// @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.
    function updateValuation(PoolId poolId, ShareClassId scId, AssetId assetId, IValuation valuation) external;

    /// @notice Updates whether the holding is a liability.
    function updateIsLiability(PoolId poolId, ShareClassId scId, AssetId assetId, bool isLiability) external;

    /// @notice Sets an account id for an specific kind
    function setAccountId(PoolId poolId, ShareClassId scId, AssetId assetId, uint8 kind, AccountId accountId)
        external;

    function setSnapshot(PoolId poolId, ShareClassId scId, uint16 tokenId, bool isSnapshot, uint64 nonce)
        external;

    function setSnapshotHook(PoolId poolId, ISnapshotHook hook) external;

    /// @notice Returns the value of this holding.
    function value(PoolId poolId, ShareClassId scId, AssetId assetId) external view returns (uint128 value);

    /// @notice Returns the amount of this holding.
    function amount(PoolId poolId, ShareClassId scId, AssetId assetId) external view returns (uint128 amount);

    /// @notice Returns the valuation method used for this holding.
    function valuation(PoolId poolId, ShareClassId scId, AssetId assetId) external view returns (IValuation);

    /// @notice Returns if the holding is a liability
    function isLiability(PoolId poolId, ShareClassId scId, AssetId assetId) external view returns (bool);

    /// @notice Returns an account id for an specific kind
    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
    function isInitialized(PoolId poolId, ShareClassId scId, AssetId assetId) external view returns (bool);
}

contracts/hub/interfaces/IHubRegistry.sol

// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;

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

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

interface IHubRegistry is IERC6909Decimals {
    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(bytes32 indexed what, address dependency);
    event UpdateCurrency(PoolId indexed poolId, AssetId currency);

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

    /// @notice Register a new asset.
    function registerAsset(AssetId assetId, uint8 decimals_) external;

    /// @notice Register a new pool.
    function registerPool(PoolId poolId, address manager, AssetId currency) external;

    /// @notice allow/disallow an address as a manager for the pool
    function updateManager(PoolId poolId, address newManager, bool canManage) external;

    /// @notice sets metadata for this pool
    function setMetadata(PoolId poolId, bytes calldata metadata) external;

    /// @notice updates a dependency of the system
    function updateDependency(bytes32 what, address dependency) external;

    /// @notice updates the currency of the pool
    function updateCurrency(PoolId poolId, AssetId currency) external;

    /// @notice returns the metadata attached to the pool, if any.
    function metadata(PoolId poolId) external view returns (bytes memory);

    /// @notice returns the currency of the pool
    function currency(PoolId poolId) external view returns (AssetId);

    /// @notice returns the dependency used in the system
    function dependency(bytes32 what) external view returns (address);

    /// @notice returns whether the account is a manager
    function manager(PoolId poolId, address who) external view returns (bool);

    /// @notice compute a pool ID given an ID postfix
    function poolId(uint16 tokenId, uint48 postfix) external view returns (PoolId poolId);

    /// @notice returns the decimals for an asset
    function decimals(AssetId assetId) external view returns (uint8);

    /// @notice returns the decimals for a pool
    function decimals(PoolId poolId) external view returns (uint8);

    /// @notice checks the existence of a pool
    function exists(PoolId poolId) external view returns (bool);

    /// @notice checks the existence of an asset
    function isRegistered(AssetId assetId) external view returns (bool);
}

contracts/misc/Auth.sol

// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;

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

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

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

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

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

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

contracts/misc/interfaces/IAuth.sol

// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;

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)
    function wards(address target) external view returns (uint256);

    /// @notice Make user a ward (give them admin access)
    function rely(address user) external;

    /// @notice Remove user as a ward (remove admin access)
    function deny(address user) external;
}

contracts/misc/interfaces/IERC165.sol

// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;

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

contracts/misc/interfaces/IERC20.sol

// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;

/// @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: ISC
pragma solidity 0.8.36;

import {IERC165} from "contracts/misc/interfaces/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/libraries/MathLib.sol

// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;

library MathLib {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero

    }

    error MulDiv_Overflow();
    error Uint8_Overflow();
    error Uint32_Overflow();
    error Uint64_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);
    }

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

    /// @notice Safe type conversion from uint256 to uint128.
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value <= type(uint128).max, Uint128_Overflow());
        return uint128(value);
    }

    /// @notice Returns the smallest of two numbers.
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? b : a;
    }

    /// @notice Returns the largest of two numbers.
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }
}

contracts/misc/types/D18.sol

// SPDX-License-Identifier: ISC
pragma solidity 0.8.36;

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

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

type D18 is uint128;

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 substract 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/division-by-zero");
    return d18(1e18, val);
}

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

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

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

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

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

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

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

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

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

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

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

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.