Skip to content
Verified contractPartialAGPL-3.0-or-later

RIVRShareClassManager

Address0x633748d72ed0d53fb118a95726ee4a98730e1fe2
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.34

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
No
License
AGPL-3.0-or-later
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,354,675
Creation transaction
0x34aab2ede7…f737299ebc

contracts/core/hub/RIVRShareClassManager.sol

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

import {IHubRegistry} from "./interfaces/IHubRegistry.sol";
import {IShareClassManager, ShareClassMetadata, Price, IssuancePerNetwork} from "./interfaces/IShareClassManager.sol";

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

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

/// @title  RIVRShareClassManager
/// @notice Manager for the share classes of a pool - handles share class creation, metadata, and share tracking
contract RIVRShareClassManager is Auth, IShareClassManager {
    IHubRegistry public immutable hubRegistry;

    mapping(bytes32 salt => bool) public salts;
    mapping(PoolId => uint32) public shareClassCount;
    mapping(PoolId => mapping(ShareClassId => bool)) public shareClassIds;
    mapping(PoolId => mapping(ShareClassId => uint128)) public totalIssuance;
    mapping(PoolId => mapping(ShareClassId => Price)) public pricePoolPerShare;
    mapping(PoolId => mapping(ShareClassId => ShareClassMetadata)) public metadata;
    mapping(PoolId => mapping(ShareClassId => mapping(uint16 rivrId => IssuancePerNetwork))) public
        issuancePerNetwork;

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

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

    /// @inheritdoc IShareClassManager
    function addShareClass(PoolId poolId, string calldata name, string calldata symbol, bytes32 salt)
        external
        auth
        returns (ShareClassId scId_)
    {
        PoolId prefixedPoolId = PoolId.wrap(uint64(bytes8(salt)));
        require(poolId == prefixedPoolId, InvalidSalt());
        require(!salts[salt], AlreadyUsedSalt());

        scId_ = previewNextShareClassId(poolId);

        uint32 index = ++shareClassCount[poolId];
        shareClassIds[poolId][scId_] = true;

        ShareClassMetadata storage meta = _updateMetadata(poolId, scId_, name, symbol);

        salts[salt] = true;
        meta.salt = salt;

        emit AddShareClass(poolId, scId_, index, name, symbol, salt);
    }

    /// @inheritdoc IShareClassManager
    function updateSharePrice(PoolId poolId, ShareClassId scId_, D18 pricePoolPerShare_, uint64 computedAt)
        external
        auth
    {
        require(exists(poolId, scId_), ShareClassNotFound());
        Price storage p = pricePoolPerShare[poolId][scId_];
        require(computedAt <= block.timestamp, CannotSetFuturePrice());

        p.price = pricePoolPerShare_;
        p.computedAt = computedAt;
        emit UpdatePricePoolPerShare(poolId, scId_, pricePoolPerShare_, computedAt);
    }

    /// @inheritdoc IShareClassManager
    function updateMetadata(PoolId poolId, ShareClassId scId_, string calldata name, string calldata symbol)
        external
        auth
    {
        require(exists(poolId, scId_), ShareClassNotFound());

        _updateMetadata(poolId, scId_, name, symbol);

        emit UpdateMetadata(poolId, scId_, name, symbol);
    }

    /// @inheritdoc IShareClassManager
    function updateShares(uint16 rivrId, PoolId poolId, ShareClassId scId_, uint128 amount, bool isIssuance)
        external
        auth
    {
        require(exists(poolId, scId_), ShareClassNotFound());

        IssuancePerNetwork storage ipn = issuancePerNetwork[poolId][scId_][rivrId];

        if (isIssuance) {
            ipn.issuances += amount;
            totalIssuance[poolId][scId_] += amount;
        } else {
            ipn.revocations += amount;
            totalIssuance[poolId][scId_] -= amount;
        }

        if (isIssuance) emit RemoteIssueShares(rivrId, poolId, scId_, amount);
        else emit RemoteRevokeShares(rivrId, poolId, scId_, amount);
    }

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

    /// @inheritdoc IShareClassManager
    function previewNextShareClassId(PoolId poolId) public view returns (ShareClassId scId) {
        return newShareClassId(poolId, shareClassCount[poolId] + 1);
    }

    /// @inheritdoc IShareClassManager
    function previewShareClassId(PoolId poolId, uint32 index) public pure returns (ShareClassId scId) {
        return newShareClassId(poolId, index);
    }

    /// @inheritdoc IShareClassManager
    function exists(PoolId poolId, ShareClassId scId_) public view returns (bool) {
        return shareClassIds[poolId][scId_];
    }

    /// @inheritdoc IShareClassManager
    function issuance(PoolId poolId, ShareClassId scId_, uint16 rivrId) public view returns (uint128) {
        IssuancePerNetwork storage ipn = issuancePerNetwork[poolId][scId_][rivrId];
        require(ipn.issuances >= ipn.revocations, NegativeIssuance());
        return ipn.issuances - ipn.revocations;
    }

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

    function _updateMetadata(PoolId poolId, ShareClassId scId_, string calldata name, string calldata symbol)
        internal
        returns (ShareClassMetadata storage meta)
    {
        uint256 nameLen = bytes(name).length;
        require(nameLen > 0 && nameLen <= 128, InvalidMetadataName());

        uint256 symbolLen = bytes(symbol).length;
        require(symbolLen > 0 && symbolLen <= 32, InvalidMetadataSymbol());

        meta = metadata[poolId][scId_];
        meta.name = name;
        meta.symbol = symbol;
    }
}

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/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/types/AssetId.sol

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

/// @dev Composite Id of the rivrId (uint16) where the asset resides
///      and a local counter (uint64) that is part of the contract that registers the asset.
type AssetId is uint128;

function isNull(AssetId assetId) pure returns (bool) {
    return AssetId.unwrap(assetId) == 0;
}

function raw(AssetId assetId) pure returns (uint128) {
    return AssetId.unwrap(assetId);
}

function rivrId(AssetId assetId) pure returns (uint16) {
    return uint16(AssetId.unwrap(assetId) >> 112);
}

function newAssetId(uint16 rivrId_, uint64 counter) pure returns (AssetId) {
    return AssetId.wrap((uint128(rivrId_) << 112) + counter);
}

function newAssetId(uint32 isoCode) pure returns (AssetId) {
    return AssetId.wrap(isoCode);
}

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

using {isNull, raw, rivrId, eq as ==} for AssetId global;

contracts/core/types/PoolId.sol

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

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

using MathLib for uint256;

type PoolId is uint64;

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

function newPoolId(uint16 rivrId_, uint48 localPoolId) pure returns (PoolId) {
    return PoolId.wrap((uint64(rivrId_) << 48) | uint64(localPoolId));
}

function isNull(PoolId poolId) pure returns (bool) {
    return PoolId.unwrap(poolId) == 0;
}

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

function raw(PoolId poolId) pure returns (uint64) {
    return PoolId.unwrap(poolId);
}

using {rivrId, isNull, raw, isEqual as ==} for PoolId global;

contracts/core/types/ShareClassId.sol

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

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

type ShareClassId is bytes16;

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

function index(ShareClassId scId) pure returns (uint32) {
    return uint32(uint128(ShareClassId.unwrap(scId)));
}

function equals(ShareClassId left, ShareClassId right) pure returns (bool) {
    return ShareClassId.unwrap(left) == ShareClassId.unwrap(right);
}

function raw(ShareClassId scId) pure returns (bytes16) {
    return ShareClassId.unwrap(scId);
}

function newShareClassId(PoolId poolId, uint32 index_) pure returns (ShareClassId scId) {
    return ShareClassId.wrap(bytes16((uint128(PoolId.unwrap(poolId)) << 64) + index_));
}

using {isNull, index, raw, equals as ==} for ShareClassId global;

contracts/misc/Auth.sol

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

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

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

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

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

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

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

contracts/misc/interfaces/IAuth.sol

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

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

    error NotAuthorized();

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

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

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

contracts/misc/interfaces/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/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/libraries/MathLib.sol

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

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

    error MulDiv_Overflow();
    error Uint8_Overflow();
    error Uint16_Overflow();
    error Uint32_Overflow();
    error Uint64_Overflow();
    error Uint96_Overflow();
    error Uint128_Overflow();
    error Int128_Overflow();

    uint256 public constant One27 = 10 ** 27;

    /// @notice Returns x^n with rounding precision of base
    ///
    /// @dev Source: https://github.com/makerdao/dss/blob/fa4f6630afb0624d04a003e920b0d71a00331d98/src/jug.sol#L62
    ///
    /// @param x The base value which should be exponentiated
    /// @param n The exponent
    /// @param base The scaling base, typically used for fix-point calculations
    function rpow(uint256 x, uint256 n, uint256 base) public pure returns (uint256 z) {
        assembly {
            switch x
            case 0 {
                switch n
                case 0 { z := base }
                default { z := 0 }
            }
            default {
                switch mod(n, 2)
                case 0 { z := base }
                default { z := x }
                let half := div(base, 2) // for rounding.
                for { n := div(n, 2) } n { n := div(n, 2) } {
                    let xx := mul(x, x)
                    if iszero(eq(div(xx, x), x)) { revert(0, 0) }
                    let xxRound := add(xx, half)
                    if lt(xxRound, xx) { revert(0, 0) }
                    x := div(xxRound, base)
                    if mod(n, 2) {
                        let zx := mul(z, x)
                        if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0, 0) }
                        let zxRound := add(zx, half)
                        if lt(zxRound, zx) { revert(0, 0) }
                        z := div(zxRound, base)
                    }
                }
            }
        }
    }

    /// @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
    ///         denominator == 0
    /// @dev    Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
    ///         with further edits by Uniswap Labs also under MIT license.
    // slither-disable-start divide-before-multiply
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, MulDiv_Overflow());

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    // slither-disable-end divide-before-multiply

    /// @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

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

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

    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value <= type(uint32).max, Uint32_Overflow());
        return uint32(value);
    }

    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value <= type(uint64).max, Uint64_Overflow());
        return uint64(value);
    }

    function toUint96(uint256 value) internal pure returns (uint96) {
        require(value <= type(uint96).max, Uint96_Overflow());
        return uint96(value);
    }

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

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

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

contracts/misc/types/D18.sol

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

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

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

type D18 is uint128;

error D18_DivisionByZero();

using MathLib for uint256;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.