// File: contracts/modules/licensing/LicenseRegistry.sol



// SPDX-License-Identifier: UNLICENSED
// See https://github.com/storyprotocol/protocol-contracts/blob/main/StoryProtocol-AlphaTestingAgreement-17942166.3.pdf
pragma solidity ^0.8.19;

import { Licensing } from "contracts/lib/modules/Licensing.sol";
import { IPAssetRegistry } from "contracts/IPAssetRegistry.sol";
import { Errors } from "contracts/lib/Errors.sol";
import { ModuleRegistry } from "contracts/modules/ModuleRegistry.sol";
import { LicensingFrameworkRepo } from "contracts/modules/licensing/LicensingFrameworkRepo.sol";
import { ERC721 } from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";
import { ShortStrings } from "@openzeppelin/contracts/utils/ShortStrings.sol";
import { Base64 } from "@openzeppelin/contracts/utils/Base64.sol";
import { LICENSING_MODULE_KEY } from "contracts/lib/modules/Module.sol";

/// @title LicenseRegistry
/// @notice This contract is the source of truth for all licenses that are registered in the protocol.
/// It will only be written by licensing modules.
/// It should not be upgradeable, so once a license is registered, it will be there forever regardless of
/// the ipOrg potentially chaning the licensing framework or Story Protocol doing upgrades.
/// Licenses can be made invalid by the revoker, according to the terms of the license.
contract LicenseRegistry is ERC721 {
    using ShortStrings for *;

    // TODO: Figure out data needed for indexing
    event LicenseRegistered(uint256 indexed id, Licensing.LicenseData licenseData);
    event LicenseNftLinkedToIpa(uint256 indexed licenseId, uint256 indexed ipAssetId);
    event LicenseActivated(uint256 indexed licenseId);
    event LicenseRevoked(uint256 indexed licenseId);

    /// license Id => LicenseData
    mapping(uint256 => Licensing.LicenseData) private _licenses;

    mapping(uint256 => Licensing.ParamValue[]) private _licenseParams;
    /// counter for license Ids
    uint256 private _licenseCount;

    IPAssetRegistry public immutable IPA_REGISTRY;
    ModuleRegistry public immutable MODULE_REGISTRY;
    LicensingFrameworkRepo public immutable LICENSING_FRAMEWORK_REPO;

    modifier onlyLicensingModule() {
        address licensingModule = address(MODULE_REGISTRY.protocolModule(LICENSING_MODULE_KEY));
        if (licensingModule != msg.sender) {
            revert Errors.LicenseRegistry_CallerNotLicensingModule();
        }
        _;
    }

    modifier onlyLicensingModuleOrLicensee(uint256 licenseId_) {
        address licensingModule = address(MODULE_REGISTRY.protocolModule(LICENSING_MODULE_KEY));
        if (licensingModule != msg.sender && msg.sender != ownerOf(licenseId_)) {
            revert Errors.LicenseRegistry_CallerNotLicensingModuleOrLicensee();
        }
        _;
    }

    modifier onlyActiveOrPending(Licensing.LicenseStatus status_) {
        if (status_ != Licensing.LicenseStatus.Active && status_ != Licensing.LicenseStatus.PendingLicensorApproval) {
            revert Errors.LicenseRegistry_InvalidLicenseStatus();
        }
        _;
    }

    modifier onlyActive(uint256 licenseId_) {
        if (!isLicenseActive(licenseId_)) {
            revert Errors.LicenseRegistry_LicenseNotActive();
        }
        _;
    }

    constructor(
        address ipaRegistry_,
        address moduleRegistry_,
        address licensingFrameworkRepo_
    ) ERC721("Story Protocol License NFT", "LNFT") {
        if (ipaRegistry_ == address(0)) {
            revert Errors.ZeroAddress();
        }
        IPA_REGISTRY = IPAssetRegistry(ipaRegistry_);
        if (moduleRegistry_ == address(0)) {
            revert Errors.ZeroAddress();
        }
        MODULE_REGISTRY = ModuleRegistry(moduleRegistry_);
        if (licensingFrameworkRepo_ == address(0)) {
            revert Errors.ZeroAddress();
        }
        LICENSING_FRAMEWORK_REPO = LicensingFrameworkRepo(licensingFrameworkRepo_);
    }

    /// Creates a tradeable License NFT.
    /// @param newLicense_ LicenseData params
    /// @param licensee_ address of the licensee
    /// @param values_ array of ParamValue structs
    /// @return licenseId_ id of the license NFT
    function addLicense(
        Licensing.LicenseData memory newLicense_,
        address licensee_,
        Licensing.ParamValue[] memory values_
    ) external onlyLicensingModule onlyActiveOrPending(newLicense_.status) returns (uint256) {
        // NOTE: check for parent ipa validity is done in
        // the licensing module
        uint256 licenseId = ++_licenseCount;
        _licenses[licenseId] = newLicense_;
        emit LicenseRegistered(licenseId, newLicense_);
        _mint(licensee_, licenseId);
        uint256 length = values_.length;
        Licensing.ParamValue[] storage params = _licenseParams[licenseId];
        for (uint256 i; i < length; i++) {
            params.push(values_[i]);
        }
        return licenseId;
    }

    /// Create a Derivate License that is reciprocal (all params are inherited
    /// from parent license)
    /// @param parentLicenseId_ id of the parent license
    /// @param licensor_ address of the licensor
    /// @param licensee_ address of the licensee
    /// @param ipaId_ id of the IPA
    /// @return licenseId_ id of the license NFT
    function addReciprocalLicense(
        uint256 parentLicenseId_,
        address licensor_,
        address licensee_,
        uint256 ipaId_
    ) external onlyLicensingModule returns (uint256) {
        if (!isLicenseActive(parentLicenseId_)) {
            revert Errors.LicenseRegistry_ParentLicenseNotActive();
        }
        Licensing.LicenseData memory clone = _licenses[parentLicenseId_];
        uint256 licenseId = ++_licenseCount;
        clone.parentLicenseId = parentLicenseId_;
        clone.licensor = licensor_;
        clone.ipaId = ipaId_;
        if (clone.derivativeNeedsApproval) {
            clone.status = Licensing.LicenseStatus.PendingLicensorApproval;
        }
        _licenseParams[licenseId] = _licenseParams[parentLicenseId_];
        _licenses[licenseId] = clone;
        emit LicenseRegistered(licenseId, clone);
        _mint(licensee_, licenseId);
        return licenseId;
    }

    /// Gets License struct for input id
    function getLicenseData(uint256 id_) public view returns (Licensing.LicenseData memory) {
        Licensing.LicenseData storage license = _licenses[id_];
        if (license.status == Licensing.LicenseStatus.Unset) {
            revert Errors.LicenseRegistry_UnknownLicenseId();
        }
        return license;
    }

    /// Gets the address granting a license, by id
    function getLicensor(uint256 id_) external view returns (address) {
        return _licenses[id_].licensor;
    }

    /// Gets the address a license is granted to
    /// @param id_ of the license
    /// @return licensee address, NFT owner if the license is tradeable, or IPA owner if bound to IPA
    function getLicensee(uint256 id_) external view returns (address) {
        return ownerOf(id_);
    }

    function getRevoker(uint256 id_) external view returns (address) {
        return _licenses[id_].revoker;
    }

    function getIPOrg(uint256 id_) external view returns (address) {
        return _licenses[id_].ipOrg;
    }

    function getIpaId(uint256 id_) external view returns (uint256) {
        return _licenses[id_].ipaId;
    }

    function getParentLicenseId(uint256 id_) external view returns (uint256) {
        return _licenses[id_].parentLicenseId;
    }

    function isReciprocal(uint256 id_) external view returns (bool) {
        return _licenses[id_].isReciprocal;
    }

    function isDerivativeAllowed(uint256 id_) external view returns (bool) {
        return _licenses[id_].derivativesAllowed;
    }

    function derivativeNeedsApproval(uint256 id_) external view returns (bool) {
        return _licenses[id_].derivativeNeedsApproval;
    }

    function getParams(uint256 id_) external view returns (Licensing.ParamValue[] memory) {
        return _licenseParams[id_];
    }

    /// Links the license to an IPA
    /// @param licenseId_ id of the license NFT
    /// @param ipaId_ id of the IPA
    function linkLnftToIpa(uint256 licenseId_, uint256 ipaId_) public onlyLicensingModuleOrLicensee(licenseId_) {
        _linkNftToIpa(licenseId_, ipaId_);
    }

    /// Checks if a license is active. If an ancestor is not active, the license is not active
    /// NOTE: this method is for alpha/illustration purposes.
    // It's implementation will require a scalability solution
    function isLicenseActive(uint256 licenseId_) public view returns (bool) {
        if (licenseId_ == 0) return false;
        while (licenseId_ != 0) {
            if (
                _licenses[licenseId_].status == Licensing.LicenseStatus.PendingLicensorApproval ||
                _licenses[licenseId_].status == Licensing.LicenseStatus.Unset ||
                _licenses[licenseId_].status == Licensing.LicenseStatus.Revoked
            ) return false;
            licenseId_ = _licenses[licenseId_].parentLicenseId;
        }
        return true;
    }

    /// Called by the licensing module to activate a license, after all the activation terms pass
    /// @param licenseId_ id of the license
    function activateLicense(uint256 licenseId_, address caller_) external onlyLicensingModule {
        _activateLicense(licenseId_, caller_);
    }

    function activateLicense(uint256 licenseId_) external {
        _activateLicense(licenseId_, msg.sender);
    }

    /// Revokes a license, making it incactive. Only the revoker can do this.
    /// NOTE: revoking licenses in an already inactive chain should be incentivized, since it
    /// reduces the while loop iterations.
    function revokeLicense(uint256 licenseId_) external {
        if (msg.sender != _licenses[licenseId_].revoker) {
            revert Errors.LicenseRegistry_CallerNotRevoker();
        }
        _licenses[licenseId_].status = Licensing.LicenseStatus.Revoked;
        // TODO: change IPA status
        emit LicenseRevoked(licenseId_);
    }

    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        Licensing.LicenseData memory license = getLicenseData(tokenId);
        // Construct the base JSON metadata with custom name format
        string memory baseJson = string(
            /* solhint-disable */
            abi.encodePacked(
                '{"name": "Story Protocol License NFT #',
                Strings.toString(tokenId),
                '", "description": "License agreement stating the terms of a Story Protocol IP Org", "attributes": ['
            )
            /* solhint-enable */
        );

        string memory licenseAttributes1 = string(
            /* solhint-disable */
            abi.encodePacked(
                '{"trait_type": "IP Org", "value": "',
                Strings.toHexString(uint160(license.ipOrg), 20),
                '"},',
                '{"trait_type": "Framework ID", "value": "',
                license.frameworkId.toString(),
                '"},',
                '{"trait_type": "Framework URL", "value": "',
                LICENSING_FRAMEWORK_REPO.getLicenseTextUrl(license.frameworkId.toString()),
                '"},',
                '{"trait_type": "Status", "value": "',
                Licensing.statusToString(license.status),
                '"},'
            )
            /* solhint-enable */
        );

        string memory licenseAttributes2 = string(
            /* solhint-disable */
            abi.encodePacked(
                '{"trait_type": "Licensor", "value": "',
                Strings.toHexString(uint160(license.licensor), 20),
                '"},',
                '{"trait_type": "Licensee", "value": "',
                Strings.toHexString(uint160(_ownerOf(tokenId)), 20),
                '"},',
                '{"trait_type": "Revoker", "value": "',
                Strings.toHexString(uint160(license.revoker), 20),
                '"},',
                '{"trait_type": "Parent License ID", "value": "',
                Strings.toString(license.parentLicenseId),
                '"},',
                '{"trait_type": "Derivative IPA", "value": "',
                Strings.toString(license.ipaId),
                '"},'
            )
            /* solhint-enable */
        );
        Licensing.ParamValue[] memory params = _licenseParams[tokenId];
        uint256 paramCount = params.length;
        string memory paramAttributes;
        for (uint256 i = 0; i < paramCount; i++) {
            Licensing.ParamDefinition memory paramDef = LICENSING_FRAMEWORK_REPO.getParamDefinition(
                license.frameworkId.toString(),
                params[i].tag
            );
            string memory value = Licensing.getDecodedParamString(paramDef, params[i].value);

            if (
                paramDef.paramType != Licensing.ParameterType.MultipleChoice &&
                paramDef.paramType != Licensing.ParameterType.ShortStringArray
            ) {
                value = string(abi.encodePacked('"', value, '"}')); // solhint-disable-line
            } else {
                value = string(abi.encodePacked(value, "}"));
            }
            paramAttributes = string(
                abi.encodePacked(
                    paramAttributes,
                    '{"trait_type": "', // solhint-disable-line
                    params[i].tag.toString(),
                    '", "value": ', // solhint-disable-line
                    value
                )
            );
            if (i != paramCount - 1) {
                paramAttributes = string(abi.encodePacked(paramAttributes, ","));
            } else {
                paramAttributes = string(abi.encodePacked(paramAttributes, "]"));
            }
        }

        return
            string(
                abi.encodePacked(
                    "data:application/json;base64,",
                    Base64.encode(
                        bytes(
                            string(
                                abi.encodePacked(baseJson, licenseAttributes1, licenseAttributes2, paramAttributes, "}")
                            )
                        )
                    )
                )
            );
    }

    function _linkNftToIpa(uint256 licenseId_, uint256 ipaId_) private onlyActive(licenseId_) {
        if (IPA_REGISTRY.status(ipaId_) != 1) {
            revert Errors.LicenseRegistry_IPANotActive();
        }
        if (_licenses[licenseId_].ipaId != 0) {
            revert Errors.LicenseRegistry_LicenseAlreadyLinkedToIpa();
        }
        _licenses[licenseId_].ipaId = ipaId_;
        emit LicenseNftLinkedToIpa(licenseId_, ipaId_);
    }

    function _activateLicense(uint256 licenseId_, address caller_) private {
        Licensing.LicenseData storage license = _licenses[licenseId_];
        if (caller_ != license.licensor) {
            revert Errors.LicenseRegistry_CallerNotLicensor();
        }
        if (license.status != Licensing.LicenseStatus.PendingLicensorApproval) {
            revert Errors.LicenseRegistry_LicenseNotPendingApproval();
        }
        if (!isLicenseActive(license.parentLicenseId)) {
            revert Errors.LicenseRegistry_ParentLicenseNotActive();
        }
        license.status = Licensing.LicenseStatus.Active;
        // TODO: change IPA status
        emit LicenseActivated(licenseId_);
    }
}

// File: contracts/lib/modules/Licensing.sol



// SPDX-License-Identifier: UNLICENSED
// See https://github.com/storyprotocol/protocol-contracts/blob/main/StoryProtocol-AlphaTestingAgreement-17942166.3.pdf
pragma solidity ^0.8.19;

import { BitMask } from "contracts/lib/BitMask.sol";
import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";
import { ShortStrings, ShortString } from "@openzeppelin/contracts/utils/ShortStrings.sol";

/// @title Licensing Module Library
library Licensing {
    using ShortStrings for *;
    /// @notice Enum for the status of a license.
    enum LicenseStatus {
        /// No status has been set.
        Unset,
        /// The license is active. It can be linked with IPAs.
        Active,
        /// The license is pending licensor approval. It can't be linked with IPAs until approved
        /// by the licensor using the LicensingModule (activateLicense)
        PendingLicensorApproval,
        /// The license has been revoked. It can't be linked with IPAs or sublicensed.
        /// Sub-licenses will be considered non active.
        Revoked
    }

    /// @notice Defines the types to encode/decode the parameters of a licensing framework.
    enum ParameterType {
        /// Boolean value
        Bool,
        /// Number value (18 decimals)
        Number,
        /// Address value
        Address,
        /// String value
        String,
        /// Array of ShortString values
        ShortStringArray,
        // uint256 bitmask representing indexes in choices array. ParamDefinition will have the available choices array.
        MultipleChoice
    }

    /// @notice Defines the configuration of the licensor for an IP org.
    enum LicensorConfig {
        /// Null value.
        Unset,
        /// Licensor is the IP org owner, for all licenses.
        IpOrgOwnerAlways,
        /// Licensor will be:
        /// - If parentLicense is provided, the licensee of the parent license.
        /// - If parentLicense is not provided, the Owner of the linked IPA.
        /// - If no parentLicense and no linked IPA, the IP org owner.
        Source
    }

    /// @notice Data struct representing a license agreement minted according to an IP Org Licensing Framework
    struct LicenseData {
        /// License status.
        LicenseStatus status;
        /// If true, other licenses can set this one as parent license, false will prevent it.
        bool derivativesAllowed;
        /// If true, sublicenses can be created by anyone, and the terms of this license will be
        /// applied to the sublicenses. If false, sublicenses can only be created by the licensor.
        bool isReciprocal;
        /// If true, sublicenses will be minted with LicenseStatus.PendingLicensorApproval.
        bool derivativeNeedsApproval;
        /// Address with permission to revoke the license.
        address revoker;
        /// address granting the license
        address licensor;
        /// address of the ip org that produced the terms
        address ipOrg;
        /// The id of the license framework used to mint this license
        ShortString frameworkId;
        /// If the licensee is linked to an IPA, this is the IPA id. 0 otherwise
        uint256 ipaId;
        /// The id of the parent license, if any. 0 otherwise
        uint256 parentLicenseId;
    }

    /// @notice Parameters to mint a license
    struct LicenseCreation {
        /// Array of (tag, value) pairs for the parameters, corresponding to the tags in the
        /// licensing framework.
        ParamValue[] params;
        /// Parent license id, if any. 0 otherwise.
        uint256 parentLicenseId;
        /// Linked IPA id, if any. 0 otherwise.
        uint256 ipaId;
    }

    /// @notice Corresponds to a parameter (licensing term) of a licensing framework.
    struct ParamDefinition {
        /// The parameter id, used to identify the parameter in the license agreement text.
        ShortString tag;
        /// The type of the parameter, used to encode/decode the value
        ParameterType paramType;
        /// Encoded according to paramType, might be empty.
        bytes defaultValue;
        /// If MultipleChoice, String[] of the available choices. Empty bytes otherwise.
        bytes availableChoices;
    }

    /// @notice Corresponds to a value for parameter (licensing term) of a licensing framework.
    struct ParamValue {
        /// The parameter id, used to identify the parameter in the license agreement text.
        ShortString tag;
        /// Encoded according to paramType, might be empty.
        bytes value;
    }

    /// @notice Parameters to set a licensing framework in LicensingFrameworkRepo
    struct SetFramework {
        /// The id of the licensing framework.
        string id;
        /// The URL to the license agreement text.
        string textUrl;
        /// Array of parameter definitions, corresponding to the parameters in
        /// the license agreement text.
        ParamDefinition[] paramDefs;
    }

    /// @notice Parameters to set a licensing framework in an IP org
    struct LicensingConfig {
        /// The id of the licensing framework.
        string frameworkId;
        /// Array of (tag, value) pairs for the parameters, corresponding to the tags in the
        /// licensing framework.
        ParamValue[] params;
        /// Enum with the rules to determine the licensor for this IP org's licenses
        LicensorConfig licensor;
    }

    /// @notice Maximum number of parameters allowed in a licensing framework.
    uint256 public constant MAX_PARAM_TAGS = 255;

    /// Input for IpOrg legal terms configuration in LicensingModule (for now, the only option)
    bytes32 public constant LICENSING_FRAMEWORK_CONFIG = keccak256("LICENSING_FRAMEWORK_CONFIG");
    /// Create license action in LicensingModule
    bytes32 public constant CREATE_LICENSE = keccak256("CREATE_LICENSE");
    /// Activate license action in LicensingModule
    bytes32 public constant ACTIVATE_LICENSE = keccak256("ACTIVATE_LICENSE");
    /// Revoke license action in LicensingModule
    bytes32 public constant LINK_LNFT_TO_IPA = keccak256("LINK_LNFT_TO_IPA");

    /// @notice Returns the string representation of a license status.
    function statusToString(LicenseStatus status_) internal pure returns (string memory) {
        if (status_ == LicenseStatus.Unset) {
            return "Unset";
        } else if (status_ == LicenseStatus.Active) {
            return "Active";
        } else if (status_ == LicenseStatus.PendingLicensorApproval) {
            return "Pending Licensor Approval";
        } else if (status_ == LicenseStatus.Revoked) {
            return "Revoked";
        }
        return "Unknown";
    }

    /// @notice decodes value from a MultipleChoice parameter into the corresponding ShortString[]
    /// with the choices
    /// @param value the encoded value
    /// @param availableChoices the encoded available choices for the parameter, defined in parameter
    /// definition
    function decodeMultipleChoice(
        bytes memory value,
        bytes memory availableChoices
    ) internal pure returns (ShortString[] memory) {
        uint256 mask = abi.decode(value, (uint256));
        uint8[] memory indexes = BitMask.getSetIndexes(mask);
        ShortString[] memory choices = abi.decode(availableChoices, (ShortString[]));
        ShortString[] memory result = new ShortString[](indexes.length);
        for (uint256 i = 0; i < indexes.length; i++) {
            result[i] = choices[indexes[i]];
        }
        return result;
    }

    /// @notice Sets the indexes for the chosen options in a MultipleChoice parameter,
    /// and encodes it into bytes
    /// @param choiceIndexes_ the indexes of the chosen options
    /// @return value the encoded value
    function encodeMultipleChoice(uint8[] memory choiceIndexes_) internal pure returns (bytes memory value) {
        uint256 mask = BitMask.convertToMask(choiceIndexes_);
        return abi.encode(mask);
    }

    /// @notice Validates the value for a parameter, according to its type, meaning it will
    /// decode the value and try to revert if it's not valid.
    /// @dev WARNING: Some validations are not possible to do on chain (like string validation),
    /// so they should be done off chain. Also, Boolean decoded as a Number will be valid.
    /// @param paramDef_ the parameter definition
    /// @param value_ the encoded value
    function validateParamValue(ParamDefinition memory paramDef_, bytes memory value_) internal pure returns (bool) {
        // An empty value signals the parameter is untagged, to trigger default values in the
        // license agreement text, but that's valid
        if (keccak256(value_) == keccak256("")) {
            return true;
        }
        if (paramDef_.paramType == Licensing.ParameterType.Bool) {
            abi.decode(value_, (bool));
            return true;
        } else if (paramDef_.paramType == Licensing.ParameterType.Number && abi.decode(value_, (uint256)) == 0) {
            return false;
        } else if (
            paramDef_.paramType == Licensing.ParameterType.Address &&
            // Not supporting address(0) as a valid value
            abi.decode(value_, (address)) == address(0)
        ) {
            return false;
        } else if (
            paramDef_.paramType == Licensing.ParameterType.String &&
            (keccak256(abi.encodePacked(abi.decode(value_, (string)))) == keccak256(abi.encode(" ")) ||
                keccak256(abi.encodePacked(abi.decode(value_, (string)))) == keccak256(abi.encode("")))
        ) {
            return false;
        } else if (
            paramDef_.paramType == Licensing.ParameterType.ShortStringArray &&
            abi.decode(value_, (ShortString[])).length == 0
        ) {
            return false;
        } else if (
            paramDef_.paramType == Licensing.ParameterType.MultipleChoice &&
            abi.decode(paramDef_.availableChoices, (ShortString[])).length == 0
        ) {
            return false;
        }
        return true;
    }

    /// @notice converts a ShortString[] to a string representation of a JSON array. Used for LicenseRegistry
    /// metadata rendering.
    /// @param ss the ShortString[]
    /// @return the string representation of a JSON array
    function shortStringArrayToJsonArray(ShortString[] memory ss) internal pure returns (string memory) {
        string memory result = "[";
        uint256 len = ss.length;
        for (uint256 i = 0; i < len; i++) {
            ShortString s = ss[i];
            result = string(abi.encodePacked(result, "\"", s.toString(), "\"")); // solhint-disable-line
            if (i != len - 1) {
                result = string(abi.encodePacked(result, ","));
            }
        }
        return string(abi.encodePacked(result, "]"));
    }

    /// @notice decodes value from a parameter into a string representation that can be used
    /// in LicenseRegistry metadata rendering.
    /// @param paramDef_ the parameter definition
    /// @param value_ the encoded value
    /// @return the string representation of the value
    function getDecodedParamString(
        Licensing.ParamDefinition memory paramDef_,
        bytes memory value_
    ) internal pure returns (string memory) {
        if (paramDef_.paramType == Licensing.ParameterType.Bool) {
            return abi.decode(value_, (bool)) ? "true" : "false";
        } else if (paramDef_.paramType == Licensing.ParameterType.Number) {
            return Strings.toString(abi.decode(value_, (uint256)));
        } else if (paramDef_.paramType == Licensing.ParameterType.String) {
            return abi.decode(value_, (string));
        } else if (paramDef_.paramType == Licensing.ParameterType.Address) {
            address addr = abi.decode(value_, (address));
            return Strings.toHexString(uint160(addr), 20);
        } else if (paramDef_.paramType == Licensing.ParameterType.ShortStringArray) {
            ShortString[] memory choices = abi.decode(value_, (ShortString[]));
            return shortStringArrayToJsonArray(choices);
        } else if (paramDef_.paramType == Licensing.ParameterType.MultipleChoice) {
            ShortString[] memory choices = decodeMultipleChoice(value_, paramDef_.availableChoices);
            return shortStringArrayToJsonArray(choices);
        }
        return "";
    }
}

// File: contracts/IPAssetRegistry.sol



// SPDX-License-Identifier: UNLICENSED
// See https://github.com/storyprotocol/protocol-contracts/blob/main/StoryProtocol-AlphaTestingAgreement-17942166.3.pdf
pragma solidity ^0.8.19;

import { IIPAssetRegistry } from "contracts/interfaces/IIPAssetRegistry.sol";
import { IRegistrationModule } from "contracts/interfaces/modules/registration/IRegistrationModule.sol";
import { IModuleRegistry } from "contracts/interfaces/modules/IModuleRegistry.sol";
import { REGISTRATION_MODULE_KEY } from "contracts/lib/modules/Module.sol";
import { Errors } from "contracts/lib/Errors.sol";

/// @title Global IP Asset Registry
/// @notice The global IP Asset Registry (GIPR) acts as the source of truth for IP
///         attribution in Story Protocol. All IP must be registered through a
///         protocol-approved registration module, which as part of the process will
///         create a record in the GIPR. Note that the GIPR only defines the core
///         attributes related to an IP asset - all other attributes, which will be
///         specific for a given module, will be queried through the module registry.
contract IPAssetRegistry is IIPAssetRegistry {
    /// @notice Core attributes that make up an IP Asset.
    struct IPA {
        string name; // Human-readable identifier for the IP asset.
        address registrant; // Address of the initial registrant of the IP asset.
        uint8 status; // Current status of the IP asset (e.g. active, expired, etc.)
        address ipOrg; // Address of the governing entity of the IP asset.
        bytes32 hash; // A unique content hash of the IP asset for preserving integrity.
        uint64 registrationDate; // Timestamp for which the IP asset was first registered.
    }

    /// @notice Used for fetching modules associated with an IP asset.
    IModuleRegistry public immutable MODULE_REGISTRY;

    /// @notice Mapping from IP asset ids to registry records.
    mapping(uint256 => IPA) internal _ipAssets;

    /// @notice Tracks the total number of IP Assets in existence.
    uint256 public totalSupply = 0;

    /// @notice Restricts calls to the registration module of the IP Asset.
    /// TODO(ramarti): Enable IPOrg-specific registration modules to be authorized.
    modifier onlyRegistrationModule() {
        if (address(MODULE_REGISTRY.protocolModule(REGISTRATION_MODULE_KEY)) != msg.sender) {
            revert Errors.Unauthorized();
        }
        _;
    }

    /// @notice Restricts calls to only being from the disputer for an IP asset.
    /// TODO(ramarti): Add authorization for calls that manage dispute lifecycle changes.
    modifier onlyDisputer(uint256 id) {
        _;
    }

    /// @notice Initializes the Global IP Asset Registry.
    /// @param moduleRegistry_ Address of the module registry.
    constructor(address moduleRegistry_) {
        MODULE_REGISTRY = IModuleRegistry(moduleRegistry_);
    }

    /// @notice Registers a new IP asset.
    /// @param registrant_ The initial registrant for the IP asset.
    /// @param name_ A name given to describe the IP asset.
    /// @param hash_ A content hash used for verifyign provenance of the asset.
    function register(
        address ipOrg_,
        address registrant_,
        string memory name_,
        bytes32 hash_
    ) public onlyRegistrationModule returns (uint256 ipAssetId) {
        // Crate a new IP asset with the provided IP attributes.
        ipAssetId = ++totalSupply;
        uint64 registrationDate = uint64(block.timestamp);
        _ipAssets[ipAssetId] = IPA({
            name: name_,
            // For now, let's assume 0 == unset, 1 is OK. TODO: Add status enum and synch with License status
            status: 1,
            registrant: registrant_,
            ipOrg: ipOrg_,
            hash: hash_,
            registrationDate: registrationDate
        });
        emit Registered(ipAssetId, name_, ipOrg_, registrant_, hash_);
    }

    /// @notice Changes the IP Org of an IP asset.
    /// @param ipAssetId_ The identifier of the IP asset being transferred.
    /// @param ipOrg_ The new IP Org to govern the IP asset.
    function transferIPOrg(uint256 ipAssetId_, address ipOrg_) public onlyRegistrationModule {
        address oldIPOrg = _ipAssets[ipAssetId_].ipOrg;
        _ipAssets[ipAssetId_].ipOrg = ipOrg_;
        emit IPOrgTransferred(ipAssetId_, oldIPOrg, ipOrg_);
    }

    /// @notice Changes the status of an IP asset.
    /// @param ipAssetId_ The identifier of the IP asset being transferred.
    /// @param status_ The new status of the IP asset.
    /// TODO(ramarti) Finalize authorization logic around status changes.
    function setStatus(uint256 ipAssetId_, uint8 status_) public onlyDisputer(ipAssetId_) {
        uint8 oldStatus = _ipAssets[ipAssetId_].status;
        _ipAssets[ipAssetId_].status = status_;
        emit StatusChanged(ipAssetId_, oldStatus, status_);
    }

    /// @notice Gets the status for a specific IP Asset.
    /// @param ipAssetId_ The id of the IP Asset being queried.
    function status(uint256 ipAssetId_) public view returns (uint8) {
        return _ipAssets[ipAssetId_].status;
    }

    /// @notice Gets the IP Asset Org that administers a specific IP Asset.
    /// @param ipAssetId_ The id of the IP asset being queried.
    function ipAssetOrg(uint256 ipAssetId_) public view returns (address) {
        return _ipAssets[ipAssetId_].ipOrg;
    }

    /// @notice Returns the current owner of an IP asset.
    /// @param ipAssetId_ The id of the IP asset being queried.
    function ipAssetOwner(uint256 ipAssetId_) public view returns (address) {
        address registrationModule = address(MODULE_REGISTRY.protocolModule(REGISTRATION_MODULE_KEY));
        return IRegistrationModule(registrationModule).ownerOf(ipAssetId_);
    }

    /// @notice Returns all attributes related to an IP asset.
    /// @param ipAssetId_ The id of the IP asset being queried for.
    function ipAsset(uint256 ipAssetId_) public view returns (IPA memory) {
        return _ipAssets[ipAssetId_];
    }
}

// File: contracts/lib/Errors.sol



// SPDX-License-Identifier: UNLICENSED
// See https://github.com/storyprotocol/protocol-contracts/blob/main/StoryProtocol-AlphaTestingAgreement-17942166.3.pdf
pragma solidity ^0.8.19;

/// @title Errors Library
/// @notice Library for all Story Protocol contract errors.
library Errors {
    ////////////////////////////////////////////////////////////////////////////
    //                                  Globals                               //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice The provided array may not be empty.
    error EmptyArray();

    /// @notice The arrays may not have a mismatch in length.
    error LengthMismatch();

    /// @notice The provided role does not exist for the given account.
    error MissingRole(bytes32 role, address account);

    /// @notice The caller is not authorized to perform the call.
    error Unauthorized();

    /// @notice The provided interface is not supported.
    error UnsupportedInterface(string name);

    /// @notice The zero address may not be used as input.
    error ZeroAddress();

    /// @notice The amount specified may not be zero.
    error ZeroAmount();

    ////////////////////////////////////////////////////////////////////////////
    //                            BaseModule                                  //
    ////////////////////////////////////////////////////////////////////////////

    error BaseModule_HooksParamsLengthMismatch(uint8 hookType);
    error BaseModule_ZeroIpaRegistry();
    error BaseModule_ZeroLicenseRegistry();
    error BaseModule_OnlyModuleRegistry();

    /// @notice The caller is not authorized to perform this operation.
    error BaseModule_Unauthorized();

    ////////////////////////////////////////////////////////////////////////////
    //                            HookRegistry                                //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice The hook is already registered.
    error HookRegistry_RegisteringDuplicatedHook();

    /// @notice This error is thrown when trying to register a hook with the address 0.
    error HookRegistry_RegisteringZeroAddressHook();

    /// @notice This error is thrown when the caller is not IP Org owner.
    error HookRegistry_CallerNotIPOrgOwner();

    /// @notice This error is thrown when trying to register more than the maximum allowed number of hooks.
    error HookRegistry_MaxHooksExceeded();

    /// @notice Hooks configuration array length does not match that of the hooks array.
    error HookRegistry_HooksConfigLengthMismatch();

    /// @notice This error is thrown when the provided index is out of bounds of the hooks array.
    error HookRegistry_IndexOutOfBounds(uint256 hooksIndex);

    /// @notice The module may not be the zero address.
    error HookRegistry_ZeroModuleRegistry();

    /// @notice The provided hook has not been whitelisted.
    error HookRegistry_RegisteringNonWhitelistedHook(address hookAddress);

    ////////////////////////////////////////////////////////////////////////////
    //                      BaseRelationshipProcessor                         //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice Call may only be processed by the relationship module.
    error BaseRelationshipProcessor_OnlyRelationshipModule();

    ////////////////////////////////////////////////////////////////////////////
    //                           ModuleRegistry                               //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice The selected module has yet to been registered.
    error ModuleRegistry_ModuleNotYetRegistered();

    /// @notice The module depenedency has not yet been registered for the gatway.
    error ModuleRegistry_DependencyNotYetRegistered();

    /// @notice The module depenedency was already registered for the gateway.
    error ModuleRegistry_DependencyAlreadyRegistered();

    /// @notice The caller is not the org owner.
    error ModuleRegistry_CallerNotOrgOwner();

    /// @notice Hook has yet to be registered.
    error ModuleRegistry_HookNotRegistered(string hookKey);

    /// @notice The selected module was already registered.
    error ModuleRegistry_ModuleAlreadyRegistered();

    /// @notice The key of the targeted module does not match the provided key.
    error ModuleRegistry_ModuleKeyMismatch();

    /// @notice The caller is not authorized to call the module dependency.
    error ModuleRegistry_Unauthorized();

    /// @notice The gateway is not valid for registration.
    error ModuleRegistry_InvalidGateway();

    ////////////////////////////////////////////////////////////////////////////
    //                                 CollectModule                          //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice Collect module caller is unauthorized.
    error CollectModule_CallerUnauthorized();

    /// @notice Collect NFT has already been initialized.
    error CollectModule_CollectNotYetInitialized();

    /// @notice Collect action is not authorized for the collect module.
    error CollectModule_CollectUnauthorized();

    /// @notice Collect module IP asset is already initialized.
    error CollectModule_IPAssetAlreadyInitialized();

    /// @notice Collect module IP asset does not exist.
    error CollectModule_IPAssetNonExistent();

    /// @notice Collect module provided IP asset registry does not exist.
    error CollectModule_IPOrgNonExistent();

    ////////////////////////////////////////////////////////////////////////////
    //                           CollectPaymentModule                         //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice The configured collect module payment amount is invalid.
    error CollectPaymentModule_AmountInvalid();

    /// @notice The ERC-20 transfer failed when processing the payment collect.
    error CollectPaymentModule_ERC20TransferFailed();

    /// @notice The collect ERC-20 transfer was not properly ABI-encoded.
    error CollectPaymentModule_ERC20TransferInvalidABIEncoding();

    /// @notice The collect ERC-20 transfer returned a non-successful value.
    error CollectPaymentModule_ERC20TransferInvalidReturnValue();

    /// @notice Invalid settings were configured for the collect payment module.
    error CollectPaymentModule_InvalidSettings();

    /// @notice Native tokens are not allowed for the configured payment module.
    error CollectPaymentModule_NativeTokenNotAllowed();

    /// @notice Native tokens failed to transfer for the payment collect.
    error CollectPaymentModule_NativeTransferFailed();

    /// @notice Invalid parameters were passed in to the payment collect.
    error CollectPaymentModule_PaymentParamsInvalid();

    /// @notice Insufficient funds were provided for the payment collect.
    error CollectPaymentModule_PaymentInsufficient();

    /// @notice The token provided for the payment collect is invalid.
    error CollectPaymentModule_TokenInvalid();

    ////////////////////////////////////////////////////////////////////////////
    //                                  CollectNFT                            //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice Collect NFT has already been initialized.
    error CollectNFT_AlreadyInitialized();

    /// @notice Caller of the Collect NFT is not authorized.
    error CollectNFT_CallerUnauthorized();

    /// @notice Collector address is not valid.
    error CollectNFT_CollectorInvalid();

    /// @notice IP asset bound to the Collect NFT does not exist.
    error CollectNFT_IPAssetNonExistent();

    ////////////////////////////////////////////////////////////////////////////
    //                                   ERC721                               //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice Originating address does not own the NFT.
    error ERC721_OwnerInvalid();

    /// @notice Receiving address cannot be the zero address.
    error ERC721_ReceiverInvalid();

    /// @notice Receiving contract does not implement the ERC-721 wallet interface.
    error ERC721_SafeTransferUnsupported();

    /// @notice Sender is not NFT owner, approved address, or owner operator.
    error ERC721_SenderUnauthorized();

    /// @notice Token has already been minted.
    error ERC721_TokenAlreadyMinted();

    /// @notice NFT does not exist.
    error ERC721_TokenNonExistent();

    ////////////////////////////////////////////////////////////////////////////
    //                                 IPAccountImpl                          //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice IP account caller is not the owner.
    error IPAccountImpl_CallerNotOwner();

    ////////////////////////////////////////////////////////////////////////////
    //                               IPAccountRegistry                        //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice IP account implementation does not exist.
    error IPAccountRegistry_NonExistentIpAccountImpl();

    /// @notice IP account initialization failed.
    error IPAccountRegistry_InitializationFailed();

    ////////////////////////////////////////////////////////////////////////////
    //                         UintArrayMask                               //
    ////////////////////////////////////////////////////////////////////////////

    error UintArrayMask_EmptyArray();

    ////////////////////////////////////////////////////////////////////////////
    //                               IPOrg                                    //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice IP identifier is over bounds.
    error IPOrg_IdOverBounds();

    /// @notice Licensing is not configured.
    error IPOrg_LicensingNotConfigured();

    /// @notice IP Org wrapper id does not exist.
    error IPOrg_IdDoesNotExist();

    ////////////////////////////////////////////////////////////////////////////
    //                             IPOrgController                            //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice The caller is not the owner of the IP Org Controller.
    error IPOrgController_InvalidOwner();

    /// @notice IP Org does not exist.
    error IPOrgController_IPOrgNonExistent();

    /// @notice The caller is not the authorized IP Org owner.
    error IPOrgController_InvalidIPOrgOwner();

    /// @notice The new owner for an IP Org may not be the zero address.
    error IPOrgController_InvalidNewIPOrgOwner();

    /// @notice The owner transfer has not yet been initialized.
    error IPOrgController_OwnerTransferUninitialized();

    ////////////////////////////////////////////////////////////////////////////
    //                                LibDuration                             //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice The caller is not the designated renwer.
    error LibDuration_CallerNotRenewer();

    /// @notice The start time is not valid.
    error LibDuration_InvalidStartTime();

    /// @notice The proposed license is not renewable.
    error LibDuration_NotRenewable();

    /// @notice A zero TTL may not be used for configuration.
    error LibDuration_ZeroTTL();

    ////////////////////////////////////////////////////////////////////////////
    //                       LicensingFrameworkRepo                           //
    ////////////////////////////////////////////////////////////////////////////
    error LicensingFrameworkRepo_FrameworkAlreadyAdded();
    error LicensingFrameworkRepo_DuplicateParamType();
    error LicensingFrameworkRepo_TooManyParams();

    ////////////////////////////////////////////////////////////////////////////
    //                        LicensingModule                                 //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice The franchise does not exist.
    error LicensingModule_CallerNotIpOrgOwner();
    error LicensingModule_InvalidConfigType();
    error LicensingModule_InvalidTermCommercialStatus();
    error LicensingModule_IpOrgFrameworkAlreadySet();
    error LicensingModule_DuplicateTermId();
    error LicensingModule_CommercialLicenseNotAllowed();
    error LicensingModule_NonCommercialTermsRequired();
    error LicensingModule_IpOrgNotConfigured();
    error LicensingModule_IpOrgAlreadyConfigured();
    error LicensingModule_ipOrgTermNotFound();
    error LicensingModule_ShareAlikeDisabled();
    error LicensingModule_InvalidAction();
    error LicensingModule_CallerNotLicensor();
    error LicensingModule_ParentLicenseNotActive();
    error LicensingModule_DerivativeNotAllowed();
    error LicensingModule_InvalidIpa();
    error LicensingModule_CallerNotLicenseOwner();
    error LicensingModule_CantFindParentLicenseOrRelatedIpa();
    error LicensingModule_InvalidLicenseeType();
    error LicensingModule_InvalidLicensorType();
    error LicensingModule_InvalidLicensorConfig();
    error LicensingModule_InvalidParamValue();
    error LicensingModule_InvalidParamsLength();
    error LicensingModule_DuplicateParam();
    error LicensingModule_ReciprocalCannotSetParams();
    error LicensingModule_ParamSetByIpOrg();
    error LicensingModule_InvalidInputValue();
    error LicensingModule_IpOrgFrameworkNotSet();

    ////////////////////////////////////////////////////////////////////////////
    //                            LicenseRegistry                             //
    ////////////////////////////////////////////////////////////////////////////

    error LicenseRegistry_UnknownLicenseId();
    error LicenseRegistry_CallerNotLicensingModule();
    error LicenseRegistry_CallerNotRevoker();
    error LicenseRegistry_CallerNotLicensingModuleOrLicensee();
    error LicenseRegistry_CallerNotLicensor();
    error LicenseRegistry_LicenseNotPendingApproval();
    error LicenseRegistry_InvalidLicenseStatus();
    error LicenseRegistry_ParentLicenseNotActive();
    error LicenseRegistry_IPANotActive();
    error LicenseRegistry_LicenseNotActive();
    error LicenseRegistry_LicenseAlreadyLinkedToIpa();

    ////////////////////////////////////////////////////////////////////////////
    //                            RegistrationModule                          //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice The caller is not authorized to perform registration.
    error RegistrationModule_CallerNotAuthorized();

    /// @notice The configured caller is invalid.
    error RegistrationModule_InvalidCaller();

    /// @notice The IP asset does not exist.
    error RegistrationModule_IPAssetNonExistent();

    /// @notice The registration module for the IP Org was not yet configured.
    error RegistrationModule_IPOrgNotConfigured();

    /// @notice The registration configuration action is not valid.
    error RegistrationModule_InvalidConfigOperation();

    /// @notice The registration execution action is not valid.
    error RegistrationModule_InvalidExecutionOperation();

    /// @notice IP asset type is not in the list of supported types for
    /// the IP Org.
    error RegistrationModule_InvalidIPAssetType();

    /// @notice IPAsset types provided are more than the maximum allowed.
    error RegistrationModule_TooManyAssetTypes();

    ////////////////////////////////////////////////////////////////////////////
    //                            RelationshipModule                          //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice Unable to relate to another franchise.
    error RelationshipModule_CannotRelateToOtherIPOrg();

    /// @notice The intent has already been registered.
    error RelationshipModule_IntentAlreadyRegistered();

    /// @notice The selected TTL is not valid.
    error RelationshipModule_InvalidTTL();

    /// @notice The selected end timestamp is not valid.
    error RelationshipModule_InvalidEndTimestamp();

    /// @notice Relationship does not exist.
    error RelationshipModule_NonExistingRelationship();

    /// @notice The relationship source IP type is not supported.
    error RelationshipModule_UnsupportedRelationshipSrc();

    /// @notice The relationship destination IP type is not supported.
    error RelationshipModule_UnsupportedRelationshipDst();

    /// @notice Trying an unsupported config action
    error RelationshipModule_InvalidConfigOperation();

    /// @notice Unauthorized caller
    error RelationshipModule_CallerNotIpOrgOwner();

    /// @notice Value not on Relatable enum
    error RelationshipModule_InvalidRelatable();

    /// @notice Getting an invalid relationship type
    error RelationshipModule_RelTypeNotSet(string relType);

    /// @notice Relating invalid src addresss
    error RelationshipModule_InvalidSrcAddress();

    /// @notice Relating invalid dst addresss
    error RelationshipModule_InvalidDstAddress();

    /// @notice Relating unsupported src ipOrg asset type
    error RelationshipModule_InvalidSrcId();

    /// @notice Relating unsupported dst ipOrg asset type
    error RelationshipModule_InvalidDstId();

    /// @notice For IPORG_ENTRY - IPORG_ENTRY relationships,
    /// ipOrg address must be set
    error RelationshipModule_IpOrgRelatableCannotBeProtocolLevel();

    /// @notice Index is not found for the asset types of that IP Org.
    error RelationshipModule_UnsupportedIpOrgIndexType();

    ////////////////////////////////////////////////////////////////////////////
    //                                RoyaltyNFT                              //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice Mismatch between parity of accounts and their respective allocations.
    error RoyaltyNFT_AccountsAndAllocationsMismatch(uint256 accountsLength, uint256 allocationsLength);

    /// @notice Invalid summation for royalty NFT allocations.
    error RoyaltyNFT_InvalidAllocationsSum(uint32 allocationsSum);

    ////////////////////////////////////////////////////////////////////////////
    //                                  Hook                                  //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice The hook request was not found.
    error Hook_RequestedNotFound();

    /// @notice The sync operation is not supported in Async hooks.
    error Hook_UnsupportedSyncOperation();

    /// @notice The async operation is not supported in Sync hooks.
    error Hook_UnsupportedAsyncOperation();

    /// @notice The callback function can only called by designated callback caller.
    error Hook_OnlyCallbackCallerCanCallback(address current, address expected);

    /// @notice Invalid async request ID.
    error Hook_InvalidAsyncRequestId(bytes32 invalidRequestId);

    /// @notice The address is not the owner of the token.
    error TokenGatedHook_NotTokenOwner(address tokenAddress, address ownerAddress);

    error Hook_AsyncHookError(bytes32 requestId, string reason);

    /// @notice Invalid Hook configuration.
    error Hook_InvalidHookConfig(string reason);

    ////////////////////////////////////////////////////////////////////////////
    //                       LicensorApprovalHook                             //
    ////////////////////////////////////////////////////////////////////////////

    error LicensorApprovalHook_ApprovalAlreadyRequested();
    error LicensorApprovalHook_InvalidLicensor();
    error LicensorApprovalHook_InvalidLicenseId();
    error LicensorApprovalHook_NoApprovalRequested();
    error LicensorApprovalHook_InvalidResponseStatus();
}

// File: contracts/modules/ModuleRegistry.sol



// SPDX-License-Identifier: UNLICENSED
// See https://github.com/storyprotocol/protocol-contracts/blob/main/StoryProtocol-AlphaTestingAgreement-17942166.3.pdf
pragma solidity ^0.8.19;

import { IModuleRegistry } from "contracts/interfaces/modules/IModuleRegistry.sol";
import { AccessControlled } from "contracts/access-control/AccessControlled.sol";
import { AccessControl } from "contracts/lib/AccessControl.sol";
import { IModule } from "contracts/interfaces/modules/base/IModule.sol";
import { IGateway } from "contracts/interfaces/modules/IGateway.sol";
import { Errors } from "contracts/lib/Errors.sol";
import { IIPOrg } from "contracts/interfaces/ip-org/IIPOrg.sol";
import { Multicall } from "@openzeppelin/contracts/utils/Multicall.sol";
import { IHook } from "contracts/interfaces/hooks/base/IHook.sol";
import { ModuleKey, ModuleDependencies, toModuleKey } from "contracts/lib/modules/Module.sol";

/// @title ModuleRegistry
/// @notice The module registry serves as the global repository for all modules
///         registered under Story Protocol, and acts as the central authorization
///         mechanism for configuring which frontends may call which modules.
contract ModuleRegistry is IModuleRegistry, AccessControlled, Multicall {
    /// @notice Identifying protocol-wide modules (opposed to those bound to specific IP Orgs).
    address public constant PROTOCOL_LEVEL = address(0);

    /// @dev Maps protocol hook string keys to their respective hooks.
    mapping(string => IHook) internal _protocolHooks;

    /// @dev Maps hook contracts to their respective hook key names.
    mapping(IHook => string) internal _hookKeys;

    /// @notice Maps module keys to their respective modules.
    mapping(ModuleKey => address) internal _modules;

    /// @notice Tracks whether a gateway can call a specific module function.
    mapping(ModuleKey => mapping(IGateway => mapping(bytes4 => bool))) internal _isAuthorized;

    constructor(address accessControl_) AccessControlled(accessControl_) {}

    /// @notice Gets the protocol-wide module associated with a module key.
    /// @param key_ The unique module key used to identify the module.
    function protocolModule(string calldata key_) public view returns (address) {
        return _modules[toModuleKey(key_)];
    }

    /// @notice Gets the protocol-wide module associated with a module key.
    /// @param key_ The unique module key used to identify the module.
    function protocolModule(ModuleKey key_) public view returns (address) {
        return _modules[key_];
    }

    /// @notice Checks whether a gateway is authorized to call a module function.
    /// @param key_ The type of the module being checked.
    /// @param gateway_ The gateway which has the module function as a dependency.
    /// @param fn_ The module function whose access is being checked for.
    function isAuthorized(ModuleKey key_, IGateway gateway_, bytes4 fn_) public view returns (bool) {
        if (_modules[key_] == address(0)) {
            revert Errors.ModuleRegistry_ModuleNotYetRegistered();
        }
        return _isAuthorized[key_][gateway_][fn_];
    }

    /// @notice Registers a new gateway to the protocol with its declared dependencies.
    /// @dev This is only callable by entities with the MODULE_REGISTRAR_ROLE role.
    /// @param gateway_ The gateway being registered into the protocol.
    function registerProtocolGateway(IGateway gateway_) external onlyRole(AccessControl.MODULE_REGISTRAR_ROLE) {
        ModuleDependencies memory dependencies = gateway_.updateDependencies();
        uint256 numModules = dependencies.keys.length;
        if (numModules != dependencies.fns.length) {
            revert Errors.ModuleRegistry_InvalidGateway();
        }

        for (uint256 i = 0; i < numModules; ++i) {
            ModuleKey moduleKey = dependencies.keys[i];
            bytes4[] memory fns = dependencies.fns[i];

            if (_modules[moduleKey] == address(0)) {
                revert Errors.ModuleRegistry_ModuleNotYetRegistered();
            }

            // Authorize all module function dependencies for the gateway.
            for (uint256 j = 0; j < fns.length; j++) {
                if (_isAuthorized[moduleKey][gateway_][fns[j]]) {
                    revert Errors.ModuleRegistry_DependencyAlreadyRegistered();
                }
                _isAuthorized[moduleKey][gateway_][fns[j]] = true;
                emit ModuleAuthorizationGranted(moduleKey, fns[j], address(gateway_), true);
            }
        }
    }

    /// @notice Removes a gatway as an authorized caller of the protocol.
    /// @dev This is only callable by entities with the MODULE_REGISTRAR_ROLE role.
    /// @param gateway_ The gateway being removed from the protocol.
    function removeProtocolGateway(IGateway gateway_) external onlyRole(AccessControl.MODULE_REGISTRAR_ROLE) {
        ModuleDependencies memory dependencies = gateway_.getDependencies();
        uint256 numModules = dependencies.keys.length;
        if (numModules != dependencies.fns.length) {
            revert Errors.ModuleRegistry_InvalidGateway();
        }

        for (uint256 i = 0; i < numModules; ++i) {
            ModuleKey moduleKey = dependencies.keys[i];
            bytes4[] memory fns = dependencies.fns[i];

            // Revoke authorizations made previously.
            // TODO: Change logic to track dependencies through the registry itself.
            for (uint256 j = 0; j < fns.length; j++) {
                if (!_isAuthorized[moduleKey][gateway_][fns[j]]) {
                    revert Errors.ModuleRegistry_DependencyNotYetRegistered();
                }
                _isAuthorized[moduleKey][gateway_][fns[j]] = false;
                emit ModuleAuthorizationGranted(moduleKey, fns[j], address(gateway_), false);
            }
        }
    }

    /// @notice Adds a new module to the protocol.
    /// @dev This is only callable by entities with the MODULE_REGISTRAR_ROLE role.
    /// @param key_ The identifier for the type of module being enrolled.
    /// @param module_ The module that will be registered into the protocol.
    function registerProtocolModule(
        ModuleKey key_,
        IModule module_
    ) external onlyRole(AccessControl.MODULE_REGISTRAR_ROLE) {
        if (address(module_) == address(0)) {
            revert Errors.ZeroAddress();
        }

        if (_modules[key_] != address(0)) {
            revert Errors.ModuleRegistry_ModuleAlreadyRegistered();
        }

        if (module_.moduleKey() != key_) {
            revert Errors.ModuleRegistry_ModuleKeyMismatch();
        }

        _modules[key_] = address(module_);

        emit ModuleAdded(PROTOCOL_LEVEL, string(abi.encodePacked(key_)), address(module_));
    }

    /// @notice Registers a new protocol hook.
    /// @param hookKey The unique identifier for the hook.
    /// @param hookAddress The address of the hook contract.
    /// @dev This function can only be called by an account with the MODULE_REGISTRAR_ROLE.
    function registerProtocolHook(
        string calldata hookKey,
        IHook hookAddress
    ) external onlyRole(AccessControl.MODULE_REGISTRAR_ROLE) {
        if (address(hookAddress) == address(0)) {
            revert Errors.ZeroAddress();
        }
        _protocolHooks[hookKey] = hookAddress;
        _hookKeys[hookAddress] = hookKey;
        emit HookAdded(PROTOCOL_LEVEL, hookKey, address(hookAddress));
    }

    /// @notice Removes a protocol hook.
    /// @param hookKey The unique identifier for the hook.
    /// @dev This function can only be called by an account with the MODULE_REGISTRAR_ROLE.
    /// If the hook is not registered, it reverts with an error.
    function removeProtocolHook(string calldata hookKey) external onlyRole(AccessControl.MODULE_REGISTRAR_ROLE) {
        if (address(_protocolHooks[hookKey]) == address(0)) {
            revert Errors.ModuleRegistry_HookNotRegistered(hookKey);
        }
        IHook hookAddress = _protocolHooks[hookKey];
        delete _protocolHooks[hookKey];
        delete _hookKeys[hookAddress];
        emit HookRemoved(PROTOCOL_LEVEL, hookKey, address(hookAddress));
    }

    /// Removes the current module configured for a module key.
    /// This is only callable by MODULE_REGISTRAR_ROLE holders.
    /// @param key_ The identifier for the type of module being removed.
    function removeProtocolModule(ModuleKey key_) external onlyRole(AccessControl.MODULE_REGISTRAR_ROLE) {
        if (_modules[key_] == address(0)) {
            revert Errors.ModuleRegistry_ModuleNotYetRegistered();
        }

        address removedModule = _modules[key_];
        delete _modules[key_];

        emit ModuleRemoved(key_, removedModule);
    }

    /// @notice Returns the protocol hook associated with a given hook key.
    /// @param hookKey The unique identifier for the hook.
    /// @return The protocol hook associated with the given hook key.
    function hookForKey(string calldata hookKey) external view returns (IHook) {
        return _protocolHooks[hookKey];
    }

    /// @notice Checks if a hook is registered in the protocol.
    /// @param hook_ The hook to check.
    /// @return True if the hook is registered, false otherwise.
    function isRegisteredHook(IHook hook_) external view returns (bool) {
        return address(_protocolHooks[_hookKeys[hook_]]) == address(hook_);
    }

    /// Execution entrypoint, callable by any address on its own behalf.
    /// @param ipOrg_ address of the IPOrg, or address(0) for protocol-level stuff
    /// @param moduleKey_ short module descriptor
    /// @param moduleParams_ encoded params for module action
    /// @param preHookParams_ encoded params for pre action hooks
    /// @param postHookParams_ encoded params for post action hooks
    /// @return encoded result of the module execution
    function execute(
        IIPOrg ipOrg_,
        string calldata moduleKey_,
        bytes memory moduleParams_,
        bytes[] memory preHookParams_,
        bytes[] memory postHookParams_
    ) external returns (bytes memory) {
        return _execute(ipOrg_, msg.sender, moduleKey_, moduleParams_, preHookParams_, postHookParams_);
    }

    /// Execution entrypoint, callable by any MODULE_EXECUTOR_ROLE holder on behalf of any address.
    /// @param ipOrg_ address of the IPOrg, or address(0) for protocol-level stuff
    /// @param caller_ address requesting the execution
    /// @param moduleKey_ short module descriptor
    /// @param moduleParams_ encoded params for module action
    /// @param preHookParams_ encoded params for pre action hooks
    /// @param postHookParams_ encoded params for post action hooks
    /// @return encoded result of the module execution
    function execute(
        IIPOrg ipOrg_,
        address caller_,
        string calldata moduleKey_,
        bytes calldata moduleParams_,
        bytes[] calldata preHookParams_,
        bytes[] calldata postHookParams_
    ) external onlyRole(AccessControl.MODULE_EXECUTOR_ROLE) returns (bytes memory) {
        return _execute(ipOrg_, caller_, moduleKey_, moduleParams_, preHookParams_, postHookParams_);
    }

    /// Configuration entrypoint, callable by any address on its own behalf.
    /// @param ipOrg_ address of the IPOrg, or address(0) for protocol-level stuff
    /// @param moduleKey_ short module descriptor
    /// @param params_ encoded params for module configuration
    function configure(IIPOrg ipOrg_, string calldata moduleKey_, bytes calldata params_) external {
        _configure(ipOrg_, msg.sender, moduleKey_, params_);
    }

    /// Configuration entrypoint, callable by any MODULE_EXECUTOR_ROLE holder on behalf of any address.
    /// @param ipOrg_ address of the IPOrg, or address(0) for protocol-level stuff
    /// @param caller_ address requesting the execution
    /// @param moduleKey_ short module descriptor
    /// @param params_ encoded params for module configuration
    function configure(
        IIPOrg ipOrg_,
        address caller_,
        string calldata moduleKey_,
        bytes calldata params_
    ) external onlyRole(AccessControl.MODULE_EXECUTOR_ROLE) returns (bytes memory) {
        return _configure(ipOrg_, caller_, moduleKey_, params_);
    }

    /// @dev Executes an action for a specific module.
    /// @param ipOrg_ The IP Org under which the execution is performed.
    /// @param caller_ The address of the original calling entity.
    /// @param moduleKey_ The identifier of the module being executed.
    /// @param moduleParams_ Encoded data to be passed to the module.
    /// @param preHookParams_ Set of data to be used for any registered pre-hooks.
    /// @param postHookParams_ Set of data to be used for any registered post-hooks.
    function _execute(
        IIPOrg ipOrg_,
        address caller_,
        string calldata moduleKey_,
        bytes memory moduleParams_,
        bytes[] memory preHookParams_,
        bytes[] memory postHookParams_
    ) private returns (bytes memory result) {
        IModule module = IModule(_modules[toModuleKey(moduleKey_)]);
        if (address(module) == address(0)) {
            revert Errors.ModuleRegistry_ModuleNotYetRegistered();
        }
        result = module.execute(ipOrg_, caller_, moduleParams_, preHookParams_, postHookParams_);
        emit ModuleExecuted(address(ipOrg_), moduleKey_, caller_, moduleParams_, preHookParams_, postHookParams_);
        return result;
    }

    /// @dev Configures a specific module for an IP Org.
    /// @param ipOrg_ The IP Org making the relevant configurations.
    /// @param caller_ The address of the calling entity performing the configuration.
    /// @param moduleKey_ The identifier for the module being configured.
    /// @param params_ Module-specific data used for the configuration.
    function _configure(
        IIPOrg ipOrg_,
        address caller_,
        string calldata moduleKey_,
        bytes calldata params_
    ) private returns (bytes memory result) {
        IModule module = IModule(_modules[toModuleKey(moduleKey_)]);
        if (address(module) == address(0)) {
            revert Errors.ModuleRegistry_ModuleNotYetRegistered();
        }
        result = module.configure(ipOrg_, caller_, params_);
        emit ModuleConfigured(address(ipOrg_), moduleKey_, caller_, params_);
        return result;
    }
}

// File: contracts/modules/licensing/LicensingFrameworkRepo.sol



// SPDX-License-Identifier: UNLICENSED
// See https://github.com/storyprotocol/protocol-contracts/blob/main/StoryProtocol-AlphaTestingAgreement-17942166.3.pdf
pragma solidity ^0.8.19;

import { Licensing } from "contracts/lib/modules/Licensing.sol";
import { ShortString, ShortStrings } from "@openzeppelin/contracts/utils/ShortStrings.sol";
import { Multicall } from "@openzeppelin/contracts/utils/Multicall.sol";
import { Errors } from "contracts/lib/Errors.sol";
import { AccessControlled } from "contracts/access-control/AccessControlled.sol";
import { AccessControl } from "contracts/lib/AccessControl.sol";
import { FixedSet } from "contracts/utils/FixedSet.sol";

/// @title Licensing Framework Repo
/// @notice Stores licensing frameworks and their parameters. License Modules
/// can use this repo to fetch the parameters of a framework in order encode and decode
/// them when creating Licenses
contract LicensingFrameworkRepo is AccessControlled, Multicall {
    using FixedSet for FixedSet.ShortStringSet;
    using ShortStrings for *;

    /// @notice Struct for storing the parameters of a licensing framework
    struct FrameworkStorage {
        /// @notice URL to the legal document of the framework
        string textUrl;
        /// @notice The tags of the parameters of the framework.
        FixedSet.ShortStringSet paramTags;
        /// @notice The definitions of the parameters of the framework
        Licensing.ParamDefinition[] paramDefs;
    }

    /// Emits when a new licensing framework is added
    event FrameworkAdded(string frameworkId, string textUrl);

    /// emits when a new parameter is added to a framework
    event ParamDefinitionAdded(string frameworkId, ShortString tag, Licensing.ParamDefinition definition);

    /// frameworkId => FrameworkStorage
    mapping(string => FrameworkStorage) private _frameworks;
    /// Hash of (frameworkId, tag) => ParamDefinition
    mapping(bytes32 => Licensing.ParamDefinition) private _frameworkDefs;

    /// @notice Constructor for the repo
    /// @param accessControl_ the address of the access control singleton contract
    constructor(address accessControl_) AccessControlled(accessControl_) {}

    /// @notice Adds a new licensing framework to the repo
    /// @dev this is an admin only function, and can only be called by the
    /// licensing manager role
    /// @param input_ the input parameters for the framework
    function addFramework(Licensing.SetFramework calldata input_) external onlyRole(AccessControl.LICENSING_MANAGER_ROLE) {
        FrameworkStorage storage framework = _frameworks[input_.id];
        if (framework.paramTags.length() > 0) {
            revert Errors.LicensingFrameworkRepo_FrameworkAlreadyAdded();
        }
        uint256 numParams = input_.paramDefs.length;
        if (numParams > Licensing.MAX_PARAM_TAGS) {
            revert Errors.LicensingFrameworkRepo_TooManyParams();
        }
        for (uint256 i = 0; i < numParams; i++) {
            _addParameter(input_.id, input_.paramDefs[i]);
        }
        framework.textUrl = input_.textUrl;
        emit FrameworkAdded(input_.id, input_.textUrl);
    }

    /// @notice Adds a new parameter to a licensing framework
    /// @param frameworkId_ the ID of the framework
    /// @param paramDef_ the definition of the parameter
    function _addParameter(string calldata frameworkId_, Licensing.ParamDefinition calldata paramDef_) internal {
        FrameworkStorage storage framework = _frameworks[frameworkId_];
        ShortString tag = paramDef_.tag;
        if (framework.paramTags.contains(tag)) {
            revert Errors.LicensingFrameworkRepo_DuplicateParamType();
        }
        framework.paramTags.add(tag);
        _frameworkDefs[keccak256(abi.encode(frameworkId_, tag))] = paramDef_;
        framework.paramDefs.push(paramDef_);
        emit ParamDefinitionAdded(frameworkId_, tag, paramDef_);
    }

    /// Gets the URL to the legal document of a licensing framework
    function getLicenseTextUrl(string calldata frameworkId_) external view returns (string memory) {
        return _frameworks[frameworkId_].textUrl;
    }

    /// Gets the definition of a parameter of a licensing framework at a
    /// given index
    /// @param frameworkId_ the ID of the framework
    /// @param index the index of the parameter
    /// @return the definition of the parameter
    function getParamDefinitionAt(
        string calldata frameworkId_,
        uint256 index
    ) external view returns (Licensing.ParamDefinition memory) {
        FrameworkStorage storage framework = _frameworks[frameworkId_];
        return framework.paramDefs[index];
    }

    /// Gets the amount of parameters of a licensing framework
    /// @param frameworkId_ the ID of the framework
    /// @return the amount of parameters
    function getTotalParameters(string calldata frameworkId_) external view returns (uint256) {
        return _frameworks[frameworkId_].paramDefs.length;
    }

    /// Gets the definition of a parameter of a licensing framework for a
    /// given tag
    /// @param frameworkId_ the ID of the framework
    /// @param tag_ the tag of the parameter
    /// @return the definition of the parameter
    function getParamDefinition(
        string calldata frameworkId_,
        ShortString tag_
    ) external view returns (Licensing.ParamDefinition memory) {
        return _frameworkDefs[keccak256(abi.encode(frameworkId_, tag_))];
    }

    /// Gets all the parameter definitions of a licensing framework
    /// @dev Warning: this function can be expensive if the framework has
    /// many parameters
    /// @param frameworkId_ the ID of the framework
    /// @return the definitions of the parameters
    function getParameterDefs(string calldata frameworkId_) external view returns (Licensing.ParamDefinition[] memory) {
        return _frameworks[frameworkId_].paramDefs;
    }
}

// File: node_modules/@openzeppelin/contracts/token/ERC721/ERC721.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/ERC721.sol)

pragma solidity ^0.8.0;

import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
    using Address for address;
    using Strings for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;

    // Mapping owner address to token count
    mapping(address => uint256) private _balances;

    // Mapping from token ID to approved address
    mapping(uint256 => address) private _tokenApprovals;

    // Mapping from owner to operator approvals
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return
            interfaceId == type(IERC721).interfaceId ||
            interfaceId == type(IERC721Metadata).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual override returns (uint256) {
        require(owner != address(0), "ERC721: address zero is not a valid owner");
        return _balances[owner];
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        address owner = _ownerOf(tokenId);
        require(owner != address(0), "ERC721: invalid token ID");
        return owner;
    }

    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        _requireMinted(tokenId);

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overridden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual override {
        address owner = ERC721.ownerOf(tokenId);
        require(to != owner, "ERC721: approval to current owner");

        require(
            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
            "ERC721: approve caller is not token owner or approved for all"
        );

        _approve(to, tokenId);
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        _requireMinted(tokenId);

        return _tokenApprovals[tokenId];
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(address from, address to, uint256 tokenId) public virtual override {
        //solhint-disable-next-line max-line-length
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");

        _transfer(from, to, tokenId);
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual override {
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
        _safeTransfer(from, to, tokenId, data);
    }

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * `data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
        _transfer(from, to, tokenId);
        require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
    }

    /**
     * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
     */
    function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
        return _owners[tokenId];
    }

    /**
     * @dev Returns whether `tokenId` exists.
     *
     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
     *
     * Tokens start existing when they are minted (`_mint`),
     * and stop existing when they are burned (`_burn`).
     */
    function _exists(uint256 tokenId) internal view virtual returns (bool) {
        return _ownerOf(tokenId) != address(0);
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
        address owner = ERC721.ownerOf(tokenId);
        return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
    }

    /**
     * @dev Safely mints `tokenId` and transfers it to `to`.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal virtual {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
        _mint(to, tokenId);
        require(
            _checkOnERC721Received(address(0), to, tokenId, data),
            "ERC721: transfer to non ERC721Receiver implementer"
        );
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal virtual {
        require(to != address(0), "ERC721: mint to the zero address");
        require(!_exists(tokenId), "ERC721: token already minted");

        _beforeTokenTransfer(address(0), to, tokenId, 1);

        // Check that tokenId was not minted by `_beforeTokenTransfer` hook
        require(!_exists(tokenId), "ERC721: token already minted");

        unchecked {
            // Will not overflow unless all 2**256 token ids are minted to the same owner.
            // Given that tokens are minted one by one, it is impossible in practice that
            // this ever happens. Might change if we allow batch minting.
            // The ERC fails to describe this case.
            _balances[to] += 1;
        }

        _owners[tokenId] = to;

        emit Transfer(address(0), to, tokenId);

        _afterTokenTransfer(address(0), to, tokenId, 1);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     * This is an internal function that does not check if the sender is authorized to operate on the token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual {
        address owner = ERC721.ownerOf(tokenId);

        _beforeTokenTransfer(owner, address(0), tokenId, 1);

        // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook
        owner = ERC721.ownerOf(tokenId);

        // Clear approvals
        delete _tokenApprovals[tokenId];

        unchecked {
            // Cannot overflow, as that would require more tokens to be burned/transferred
            // out than the owner initially received through minting and transferring in.
            _balances[owner] -= 1;
        }
        delete _owners[tokenId];

        emit Transfer(owner, address(0), tokenId);

        _afterTokenTransfer(owner, address(0), tokenId, 1);
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(address from, address to, uint256 tokenId) internal virtual {
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
        require(to != address(0), "ERC721: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId, 1);

        // Check that tokenId was not transferred by `_beforeTokenTransfer` hook
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");

        // Clear approvals from the previous owner
        delete _tokenApprovals[tokenId];

        unchecked {
            // `_balances[from]` cannot overflow for the same reason as described in `_burn`:
            // `from`'s balance is the number of token held, which is at least one before the current
            // transfer.
            // `_balances[to]` could overflow in the conditions described in `_mint`. That would require
            // all 2**256 token ids to be minted, which in practice is impossible.
            _balances[from] -= 1;
            _balances[to] += 1;
        }
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        _afterTokenTransfer(from, to, tokenId, 1);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits an {Approval} event.
     */
    function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Emits an {ApprovalForAll} event.
     */
    function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
        require(owner != operator, "ERC721: approve to caller");
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Reverts if the `tokenId` has not been minted yet.
     */
    function _requireMinted(uint256 tokenId) internal view virtual {
        require(_exists(tokenId), "ERC721: invalid token ID");
    }

    /**
     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
     * The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param data bytes optional data to send along with the call
     * @return bool whether the call correctly returned the expected magic value
     */
    function _checkOnERC721Received(
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) private returns (bool) {
        if (to.isContract()) {
            try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
                return retval == IERC721Receiver.onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert("ERC721: transfer to non ERC721Receiver implementer");
                } else {
                    /// @solidity memory-safe-assembly
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is
     * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.
     * - When `from` is zero, the tokens will be minted for `to`.
     * - When `to` is zero, ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     * - `batchSize` is non-zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}

    /**
     * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is
     * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.
     * - When `from` is zero, the tokens were minted for `to`.
     * - When `to` is zero, ``from``'s tokens were burned.
     * - `from` and `to` are never both zero.
     * - `batchSize` is non-zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}

    /**
     * @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
     *
     * WARNING: Anyone calling this MUST ensure that the balances remain consistent with the ownership. The invariant
     * being that for any address `a` the value returned by `balanceOf(a)` must be equal to the number of tokens such
     * that `ownerOf(tokenId)` is `a`.
     */
    // solhint-disable-next-line func-name-mixedcase
    function __unsafe_increaseBalance(address account, uint256 amount) internal {
        _balances[account] += amount;
    }
}

// File: node_modules/@openzeppelin/contracts/utils/Strings.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/Math.sol";
import "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toString(int256 value) internal pure returns (string memory) {
        return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

// File: node_modules/@openzeppelin/contracts/utils/ShortStrings.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/ShortStrings.sol)

pragma solidity ^0.8.8;

import "./StorageSlot.sol";

// | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |
// | length  | 0x                                                              BB |
type ShortString is bytes32;

/**
 * @dev This library provides functions to convert short memory strings
 * into a `ShortString` type that can be used as an immutable variable.
 *
 * Strings of arbitrary length can be optimized using this library if
 * they are short enough (up to 31 bytes) by packing them with their
 * length (1 byte) in a single EVM word (32 bytes). Additionally, a
 * fallback mechanism can be used for every other case.
 *
 * Usage example:
 *
 * ```solidity
 * contract Named {
 *     using ShortStrings for *;
 *
 *     ShortString private immutable _name;
 *     string private _nameFallback;
 *
 *     constructor(string memory contractName) {
 *         _name = contractName.toShortStringWithFallback(_nameFallback);
 *     }
 *
 *     function name() external view returns (string memory) {
 *         return _name.toStringWithFallback(_nameFallback);
 *     }
 * }
 * ```
 */
library ShortStrings {
    // Used as an identifier for strings longer than 31 bytes.
    bytes32 private constant _FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;

    error StringTooLong(string str);
    error InvalidShortString();

    /**
     * @dev Encode a string of at most 31 chars into a `ShortString`.
     *
     * This will trigger a `StringTooLong` error is the input string is too long.
     */
    function toShortString(string memory str) internal pure returns (ShortString) {
        bytes memory bstr = bytes(str);
        if (bstr.length > 31) {
            revert StringTooLong(str);
        }
        return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
    }

    /**
     * @dev Decode a `ShortString` back to a "normal" string.
     */
    function toString(ShortString sstr) internal pure returns (string memory) {
        uint256 len = byteLength(sstr);
        // using `new string(len)` would work locally but is not memory safe.
        string memory str = new string(32);
        /// @solidity memory-safe-assembly
        assembly {
            mstore(str, len)
            mstore(add(str, 0x20), sstr)
        }
        return str;
    }

    /**
     * @dev Return the length of a `ShortString`.
     */
    function byteLength(ShortString sstr) internal pure returns (uint256) {
        uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
        if (result > 31) {
            revert InvalidShortString();
        }
        return result;
    }

    /**
     * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
     */
    function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
        if (bytes(value).length < 32) {
            return toShortString(value);
        } else {
            StorageSlot.getStringSlot(store).value = value;
            return ShortString.wrap(_FALLBACK_SENTINEL);
        }
    }

    /**
     * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
     */
    function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
        if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
            return toString(value);
        } else {
            return store;
        }
    }

    /**
     * @dev Return the length of a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
     *
     * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
     * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
     */
    function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
        if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
            return byteLength(value);
        } else {
            return bytes(store).length;
        }
    }
}

// File: node_modules/@openzeppelin/contracts/utils/Base64.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides a set of functions to operate with Base64 strings.
 *
 * _Available since v4.5._
 */
library Base64 {
    /**
     * @dev Base64 Encoding/Decoding Table
     */
    string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    /**
     * @dev Converts a `bytes` to its Bytes64 `string` representation.
     */
    function encode(bytes memory data) internal pure returns (string memory) {
        /**
         * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
         * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
         */
        if (data.length == 0) return "";

        // Loads the table into memory
        string memory table = _TABLE;

        // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter
        // and split into 4 numbers of 6 bits.
        // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up
        // - `data.length + 2`  -> Round up
        // - `/ 3`              -> Number of 3-bytes chunks
        // - `4 *`              -> 4 characters for each chunk
        string memory result = new string(4 * ((data.length + 2) / 3));

        /// @solidity memory-safe-assembly
        assembly {
            // Prepare the lookup table (skip the first "length" byte)
            let tablePtr := add(table, 1)

            // Prepare result pointer, jump over length
            let resultPtr := add(result, 32)

            // Run over the input, 3 bytes at a time
            for {
                let dataPtr := data
                let endPtr := add(data, mload(data))
            } lt(dataPtr, endPtr) {

            } {
                // Advance 3 bytes
                dataPtr := add(dataPtr, 3)
                let input := mload(dataPtr)

                // To write each character, shift the 3 bytes (18 bits) chunk
                // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
                // and apply logical AND with 0x3F which is the number of
                // the previous character in the ASCII table prior to the Base64 Table
                // The result is then added to the table to get the character to write,
                // and finally write it in the result pointer but with a left shift
                // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits

                mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance
            }

            // When data `bytes` is not exactly 3 bytes long
            // it is padded with `=` characters at the end
            switch mod(mload(data), 3)
            case 1 {
                mstore8(sub(resultPtr, 1), 0x3d)
                mstore8(sub(resultPtr, 2), 0x3d)
            }
            case 2 {
                mstore8(sub(resultPtr, 1), 0x3d)
            }
        }

        return result;
    }
}

// File: contracts/lib/modules/Module.sol



// SPDX-License-Identifier: UNLICENSED
// See https://github.com/storyprotocol/protocol-contracts/blob/main/StoryProtocol-AlphaTestingAgreement-17942166.3.pdf
pragma solidity ^0.8.19;

// This file contains module structures and constants used throughout Story Protocol.

// A module key is identified by its keccak-256 encoded string identifier.
type ModuleKey is bytes32;

using { moduleKeyEquals as == } for ModuleKey global;
using { moduleKeyNotEquals as != } for ModuleKey global;

// A gateway's module dependencies are composed of a list of module keys
// and a list of function selectors dependend on for each of these modules.
struct ModuleDependencies {
    ModuleKey[] keys;
    bytes4[][] fns;
}

// Helper function for comparing equality between two keys.
function moduleKeyEquals(ModuleKey k1, ModuleKey k2) pure returns (bool) {
    return ModuleKey.unwrap(k1) == ModuleKey.unwrap(k2);
}

// Helper function for comparing inequality between two keys.
function moduleKeyNotEquals(ModuleKey k1, ModuleKey k2) pure returns (bool) {
    return ModuleKey.unwrap(k1) != ModuleKey.unwrap(k2);
}

// Transforms a string to its designated module key.
function toModuleKey(string calldata moduleKey_) pure returns (ModuleKey) {
    return ModuleKey.wrap(keccak256(abi.encodePacked(moduleKey_)));
}

// String values for core protocol modules.
string constant RELATIONSHIP_MODULE = "RELATIONSHIP_MODULE";
string constant LICENSING_MODULE = "LICENSING_MODULE";
string constant REGISTRATION_MODULE = "REGISTRATION_MODULE";

// Module key values for core protocol modules.
ModuleKey constant RELATIONSHIP_MODULE_KEY = ModuleKey.wrap(keccak256(abi.encodePacked(RELATIONSHIP_MODULE)));
ModuleKey constant LICENSING_MODULE_KEY = ModuleKey.wrap(keccak256(abi.encodePacked(LICENSING_MODULE)));
ModuleKey constant REGISTRATION_MODULE_KEY = ModuleKey.wrap(keccak256(abi.encodePacked(REGISTRATION_MODULE)));

// File: contracts/lib/BitMask.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

/**
 * @notice Based on OpenZeppelin's BitMap, this library is used to encode a set of indexes in a compact way.
 * Instead of using a storage type like OZ, where they use a mapping(uint256 => uint256) for large numbers of values,
 * this library limts it to a 256 values in a single uint256.
 */
library BitMask {
    /// Returns whether the bit at `index` is set.
    function isSet(uint256 mask_, uint8 index_) internal pure returns (bool) {
        uint256 indexMask = 1 << (index_ & 0xff);
        return mask_ & indexMask != 0;
    }

    /// Sets the bit at `index` to the boolean `value`.
    function setTo(uint256 mask_, uint256 index_, bool value_) internal pure returns (uint256) {
        if (value_) {
            return set(mask_, index_);
        } else {
            return unset(mask_, index_);
        }
    }

    /// Sets the bit at `index`.
    function set(uint256 mask_, uint256 index_) internal pure returns (uint256) {
        uint256 indexMask = 1 << (index_ & 0xff);
        return mask_ |= indexMask;
    }

    /// Unsets the bit at `index`.
    function unset(uint256 mask_, uint256 index_) internal pure returns (uint256) {
        uint256 indexMask = 1 << (index_ & 0xff);
        return mask_ &= ~indexMask;
    }

    /// Gets the uint8 from the bitmask as an array
    function getSetIndexes(uint256 mask_) internal pure returns (uint8[] memory) {
        // Count the number of set bits to allocate the array size
        uint256 count;
        for (uint8 i = 0; i < 255; ++i) {
            if (isSet(mask_, i)) {
                ++count;
            }
        }
        uint8[] memory setBitIndexes = new uint8[](count);
        // Fill the array with indices of set bits
        uint256 index = 0;
        for (uint8 i = 0; i < 255; ++i) {
            if (isSet(mask_, i)) {
                setBitIndexes[index] = i;
                ++index;
            }
        }
        return setBitIndexes;
    }

    /// Converts an array of uint8 to a bit mask
    function convertToMask(uint8[] memory indexes_) internal pure returns (uint256) {
        uint256 mask = 0;
        for (uint256 i = 0; i < indexes_.length; ) {
            mask |= 1 << (uint256(indexes_[i]) & 0xff);
            unchecked {
                i++;
            }
        }
        return mask;
    }
}

// File: contracts/interfaces/IIPAssetRegistry.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

/// @title Global IP Asset Registry Interface
interface IIPAssetRegistry {
    /// @notice Emits when a new IP asset is registered.
    /// @param ipAssetId_ The global IP asset identifier.
    /// @param name_ The assigned name for the IP asset.
    /// @param ipOrg_ The registering governing body for the IP asset.
    /// @param registrant_ The initial individual registrant of the IP asset.
    /// @param hash_ The content hash associated with the IP asset.
    event Registered(
        uint256 ipAssetId_,
        string name_,
        address indexed ipOrg_,
        address indexed registrant_,
        bytes32 hash_
    );

    /// @notice Emits when an IP asset is transferred to a new IP Org.
    /// @param ipAssetId_ The identifier of the IP asset being transferred.
    /// @param oldIPOrg_ The original administering IP Org of the IP asset.
    /// @param newIPOrg_ The new administering IP Org of the IP asset.
    event IPOrgTransferred(uint256 indexed ipAssetId_, address indexed oldIPOrg_, address indexed newIPOrg_);

    /// @notice Emits when an IP asset has its status changed.
    /// @param ipAssetId_ The identifier of the IP asset whose status changed.
    /// @param oldStatus_ The original status associated with the IP asset.
    /// @param newStatus_ The new status associated with the IP asset.
    event StatusChanged(uint256 indexed ipAssetId_, uint8 oldStatus_, uint8 newStatus_);
}

// File: contracts/interfaces/modules/registration/IRegistrationModule.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import { IModule } from "contracts/interfaces/modules/base/IModule.sol";

/// @title IRegistrationModule
interface IRegistrationModule is IModule {
    /// @notice Emits when an IPOrg updates metadata associated with its IPA.
    /// @param ipOrg The address of the IP Org whose metadata was updated.
    /// @param baseURI The base token URI to be used for token metadata.
    /// @param contractURI The contract URI to be used for contract metadata.
    event MetadataUpdated(address indexed ipOrg, string baseURI, string contractURI);

    /// @notice Emits when a new IP asset is registered.
    /// @param ipAssetId The identifier of the newly registered IP asset.
    /// @param ipOrg The address of the IP Org of the IP asset.
    /// @param ipOrgAssetId The IP Org localized id of the IP asset.
    /// @param owner The address of the new IP asset owner.
    /// @param name The name of the IP asset being registered.
    /// @param ipOrgAssetType The numerical id of the IP asset type.
    /// @param hash The content hash of the registered IP asset.
    /// @param mediaUrl The media URL of the registered IP asset.
    event IPAssetRegistered(
        uint256 ipAssetId,
        address indexed ipOrg,
        uint256 ipOrgAssetId,
        address indexed owner,
        string name,
        uint8 indexed ipOrgAssetType,
        bytes32 hash,
        string mediaUrl
    );

    /// @notice Emits when an IP asset is transferred to a new owner.
    /// @param ipAssetId The identifier of the IP asset being transferred.
    /// @param ipOrg The address of the IP Org which administers the IP asset.
    /// @param ipOrgAssetId The local id of the wrapped IP within the IP Org.
    /// @param prevOwner The address of the previous owner of the IP asset.
    /// @param newOwner The address of the new owner of the IP asset.
    event IPAssetTransferred(
        uint256 indexed ipAssetId,
        address indexed ipOrg,
        uint256 ipOrgAssetId,
        address prevOwner,
        address newOwner
    );

    /// @notice Returns the current owner of an IP asset.
    /// @param ipAssetId_ The global identifier of the IP asset within the GIPR.
    function ownerOf(uint256 ipAssetId_) external view returns (address);

    /// @notice Gets the IP asset id associated with an IP Org asset.
    /// @param ipOrg_ The address of the governing IP asset IP Org.
    /// @param ipOrgAssetId_ The localized id of the IP asset within the IP Org.
    function ipAssetId(address ipOrg_, uint256 ipOrgAssetId_) external view returns (uint256);

    /// @notice Renders metadata of an IP Asset localized for an IP Org.
    /// @param ipOrg_ The address of the IP Org of the IP asset.
    /// @param ipOrgAssetId_ The local id of the IP asset within the IP Org.
    /// @param ipOrgAssetType_ The IP Org asset type.
    /// @return The token URI associated with the IP Org.
    function tokenURI(
        address ipOrg_,
        uint256 ipOrgAssetId_,
        uint8 ipOrgAssetType_
    ) external view returns (string memory);

    /// @notice Gets the contract URI for an IP Org.
    /// @param ipOrg_ The address of the IP Org.
    /// @return The contract URI associated with the IP Org.
    function contractURI(address ipOrg_) external view returns (string memory);

    /// @notice get the ip Asset types of an ipOrg
    function getIpOrgAssetTypes(address ipOrg_) external view returns (string[] memory);

    /// @notice Returns true if the index for an IP Org asset type is supported.
    function isValidIpOrgAssetType(address ipOrg_, uint8 index) external view returns (bool);
}

// File: contracts/interfaces/modules/IModuleRegistry.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import { ModuleKey } from "contracts/lib/modules/Module.sol";
import { IGateway } from "contracts/interfaces/modules/IGateway.sol";
import { IModule } from "contracts/interfaces/modules/base/IModule.sol";

/// @title IModuleRegistry
/// @notice Module Registry Interface
interface IModuleRegistry {
    /// @notice Emits when a gateway was successfully registered by the protocol
    ///         for a specific dependency (module type + module function).
    /// @param key The identifier of the dependent module type.
    /// @param fn The function identifier of the dependent module type.
    /// @param gateway The gateway address granted permission to use the dependency.
    /// @param grant Whether the gateway was authorized to use the dependency.
    event ModuleAuthorizationGranted(ModuleKey indexed key, bytes4 fn, address indexed gateway, bool grant);

    /// @notice Emits when a brand new module is enrolled to the protocol.
    /// @param ipOrg The IP Org to which the module belongs.
    /// @param moduleKey The string identifier of the module type that was added.
    /// @param module The address of the module.
    event ModuleAdded(address indexed ipOrg, string moduleKey, address indexed module);

    /// @notice Emits when the protocol module for a module type is removed.
    /// @param key The identifier of the module type that was added.
    /// @param module The address of the removed module
    event ModuleRemoved(ModuleKey indexed key, address indexed module);

    /// @notice Emits when a module is executed for an IP Org.
    event ModuleExecuted(
        address indexed ipOrg,
        string moduleKey,
        address indexed caller,
        bytes selfParams,
        bytes[] preHookParams,
        bytes[] postHookParams
    );

    /// @notice Emits when a module is configured for an IP Org.
    event ModuleConfigured(address indexed ipOrg, string moduleKey, address indexed caller, bytes params);

    /// @notice Emits when a new hook is added for a specific IP Org.
    event HookAdded(address indexed ipOrg, string hookKey, address indexed hook);

    /// @notice Emits when a hook is removed for an IP Org.
    event HookRemoved(address indexed ipOrg, string hookKey, address indexed hook);

    /// @notice Registers a new module of a provided type to Story Protocol.
    /// @param key_ The bytes32 type of the module being registered.
    /// @param module_ The actual module being registered.
    function registerProtocolModule(ModuleKey key_, IModule module_) external;

    /// @notice Fetches the protocol module by its string identifier.
    /// @param key_ The string module type.
    /// @return The module associated with the module key.
    function protocolModule(string calldata key_) external view returns (address);

    /// @notice Fetches the protocol module bound to a module type.
    /// @param key_ The bytes32 module type.
    /// @return The module associated with the module key.
    function protocolModule(ModuleKey key_) external view returns (address);

    /// @notice Checks whether a gateway has permission to call a module function.
    /// @param key_ The module type.
    /// @param gateway_ The gateway which has the module as a dependency.
    /// @param fn_ The module function whose access is being checked for.
    function isAuthorized(ModuleKey key_, IGateway gateway_, bytes4 fn_) external view returns (bool);
}

// File: contracts/access-control/AccessControlled.sol



// SPDX-License-Identifier: UNLICENSED
// See https://github.com/storyprotocol/protocol-contracts/blob/main/StoryProtocol-AlphaTestingAgreement-17942166.3.pdf
pragma solidity ^0.8.19;

// solhint-disable-next-line max-line-length
import { ERC165CheckerUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165CheckerUpgradeable.sol";
import { IAccessControl } from "@openzeppelin/contracts/access/IAccessControl.sol";

import { AccessControl } from "contracts/lib/AccessControl.sol";
import { IAccessControlled } from "contracts/interfaces/access-control/IAccessControlled.sol";
import { Errors } from "contracts/lib/Errors.sol";

/// @title Access Controlled Contract
/// @notice This contract is to be inherited by any protocol components that require granular
///         roles for execution, as defined by the Access Control Singleton contract. Later on,
///         this contract will be deprecated in favor of authorization through te module registry.
abstract contract AccessControlled is IAccessControlled {
    using ERC165CheckerUpgradeable for address;

    /// @notice Pointer to the global Access Control Singleton for protocol auth.
    IAccessControl private _accessControl;

    /// @notice Checks if msg.sender has role `role`, reverts otherwise.
    /// @param role_ The role being checked for, set by the Access Control Singleton.
    modifier onlyRole(bytes32 role_) {
        if (!_hasRole(role_, msg.sender)) {
            revert Errors.MissingRole(role_, msg.sender);
        }
        _;
    }

    /// @notice Instantiates a new Access Controlled contract.
    /// @param accessControl_ The global Access Control Singleton contract address.
    constructor(address accessControl_) {
        if (!accessControl_.supportsInterface(type(IAccessControl).interfaceId))
            revert Errors.UnsupportedInterface("IAccessControl");
        _accessControl = IAccessControl(accessControl_);
        emit AccessControlUpdated(accessControl_);
    }

    /// @notice Sets the Access Control Singleton used for authorization.
    /// @param accessControl_ The address of the new Access Control Singleton.
    function setAccessControl(address accessControl_) public onlyRole(AccessControl.PROTOCOL_ADMIN_ROLE) {
        if (!accessControl_.supportsInterface(type(IAccessControl).interfaceId))
            revert Errors.UnsupportedInterface("IAccessControl");
        _accessControl = IAccessControl(accessControl_);
        emit AccessControlUpdated(accessControl_);
    }

    /// @dev Checks if an account `account_` has role `role_` assigned.
    /// @param role_ The role being checked for as defined by the Access Control Singlton.
    /// @param account_ The address whose role permissions are being checked for.
    /// @return return True if the account has the role, False otherwise.
    function _hasRole(bytes32 role_, address account_) internal view returns (bool) {
        return _accessControl.hasRole(role_, account_);
    }
}

// File: contracts/lib/AccessControl.sol



// SPDX-License-Identifier: UNLICENSED
// See https://github.com/storyprotocol/protocol-contracts/blob/main/StoryProtocol-AlphaTestingAgreement-17942166.3.pdf
pragma solidity ^0.8.19;

/// @title Access Control Library
/// @notice Library for access control helpers and protocol role definitions.
///         These roles are used by the AccessControlSingleton, accessed by AccessControlled contracts.
library AccessControl {
    // Default admin role as per OZ AccessControl system. All other roles stem from this.
    bytes32 public constant PROTOCOL_ADMIN_ROLE = bytes32(0);

    // Role that can upgrade UUPS contracts or Beacon Proxies
    bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");

    // Role for managing protocol-wide and IP Org localized relationships.
    bytes32 public constant RELATIONSHIP_MANAGER_ROLE = keccak256("RELATIONSHIP_MANAGER_ROLE");

    // Role that can perform admin tasks on the Licensing Module contracts (setNonCommercialLicenseURI)
    bytes32 public constant LICENSING_MANAGER_ROLE = keccak256("LICENSING_MANAGER_ROLE");

    // Role that can add new modules to the Module Registry
    bytes32 public constant MODULE_REGISTRAR_ROLE = keccak256("MODULE_REGISTRAR_ROLE");

    // Role that can execute modules
    bytes32 public constant MODULE_EXECUTOR_ROLE = keccak256("MODULE_EXECUTOR_ROLE");

    // Role that can execute Hooks
    bytes32 public constant HOOK_CALLER_ROLE = keccak256("HOOK_CALLER_ROLE");

}

// File: contracts/interfaces/modules/base/IModule.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import { IIPOrg } from "contracts/interfaces/ip-org/IIPOrg.sol";
import { ModuleKey } from "contracts/lib/modules/Module.sol";

/// @title Story Protocol Module Interface.
/// @notice This interface must be implemented by all protocol modules in Story Protocol,
///         providing the base functionality needed for authorization and execution
///         logic centered around IP assets.
interface IModule {
    /// The execution of the module is pending, and will need to be executed again.
    event RequestPending(address indexed sender);
    /// Module execution completed successfully.
    event RequestCompleted(address indexed sender);
    /// Module execution failed.
    event RequestFailed(address indexed sender, string reason);

    /// @notice Gets the protocol-wide key associated with the module.
    /// @return The bytes32 identifier of the module.
    function moduleKey() external pure returns (ModuleKey);

    /// @notice Main execution entrypoint.
    /// @dev This function verifies encoded module params, executes any pre-action hooks,
    ///      performs the main module logic, and then executes any post-action hooks.
    ///      Modules must decide themselves how parameters are encoded and decoded.
    /// @param ipOrg_ Address of the IP Org or the zero address (for protocol-wide modules).
    /// @param caller_ Address of the caller.
    /// @param moduleParams_ Encoded params to be decoded for module execution.
    /// @param preHookParams_ Encoded params used for pre-hook execution logic.
    /// @param postHookParams_ Encoded params used for post-hook execution logic.
    /// @return result of the module action
    function execute(
        IIPOrg ipOrg_,
        address caller_,
        bytes calldata moduleParams_,
        bytes[] calldata preHookParams_,
        bytes[] calldata postHookParams_
    ) external returns (bytes memory result);

    /// @notice Module configuration entrypoint.
    /// @dev Note that it is up to the module on how the parameters should be
    ///      encoded, unpacked, and used for configuration.
    /// @param ipOrg_ Address of the IP Org or the zero address (for protocol-wide modules).
    /// @param caller_ Address of configuration caller.
    /// @param params_ ABI-encoded parameters used for module configuration.
    /// @return result Result of the module configuration expressed as a bytes array.
    function configure(IIPOrg ipOrg_, address caller_, bytes calldata params_) external returns (bytes memory result);
}

// File: contracts/interfaces/modules/IGateway.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import { ModuleDependencies } from "contracts/lib/modules/Module.sol";

/// @title Module Gateway Interface
/// @notice Interface for a Story Protocol module gateway, which is a contract
///         that may be granted access by the module registry to call module
///         functions declared by the gateway's module dependency set.
interface IGateway {
    /// @notice Synchronizes all downstream dependencies via the module registry.
    /// @dev This function may only be called by the module registry.
    /// @return dependencies The freshly updated dependencies needed by the gateway.
    function updateDependencies() external returns (ModuleDependencies memory dependencies);

    /// @notice Fetches all module dependencies required by the gateway contract.
    /// @return dependencies The dependencies that the gateway requires from the protocol.
    function getDependencies() external view returns (ModuleDependencies memory dependencies);
}

// File: contracts/interfaces/ip-org/IIPOrg.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

/// @notice IP Org Interface
interface IIPOrg {
    /// @notice Returns the current owner of the IP asset within the IP Org.
    /// @return The address of the owner of the IP asset.
    function ownerOf(uint256 id) external view returns (address);

    /// @notice Transfers ownership of the IP asset wrapper within an IP Org.
    /// @param from The previous owner of the wrapped IP asset.
    /// @param to The new owner of the wrapped IP asset.
    /// @param id The identifier of the IP Org asset.
    function transferFrom(address from, address to, uint256 id) external;

    /// @notice Burns an IP asset wrapper within the IP Org.
    /// @dev This function is only callable by the IP Org registration module.
    /// @param id The local identifier of the IP asset within the IP Org.
    function burn(uint256 id) external;

    /// @notice Mints an IP Asset wrapper for the IP Org.
    /// @dev This function is only callable by the IP Org registration module.
    /// @param owner Address of the current owner of the local IP Org asset.
    /// @param assetType The IP Org asset type.
    /// @return id The local identifier of the minted IP Org wrapped asset.
    function mint(address owner, uint8 assetType) external returns (uint256 id);

    /// @notice Gets the current owner of the IP Org.
    /// @return The address of the IP Org owner.
    function owner() external view returns (address);

    /// @notice Returns contract-level metadata for the IP Org.
    /// @return The contract-wide URI associated with the IP Org.
    function contractURI() external view returns (string memory);

    /// @notice Returns the IP Org asset type for a given IP Org asset.
    /// @return The id associated with the IP Org asset type.
    function ipOrgAssetType(uint256 id_) external view returns (uint8);

    /// @notice Gets the global IP asset id associated with this IP Org asset.
    /// @param id_ The local id of the IP Org wrapped IP asset.
    /// @return The global identifier of the IP asset.
    function ipAssetId(uint256 id_) external returns (uint256);
}

// File: node_modules/@openzeppelin/contracts/utils/Multicall.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Multicall.sol)

pragma solidity ^0.8.0;

import "./Address.sol";

/**
 * @dev Provides a function to batch together multiple calls in a single external call.
 *
 * _Available since v4.1._
 */
abstract contract Multicall {
    /**
     * @dev Receives and executes a batch of function calls on this contract.
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {
        results = new bytes[](data.length);
        for (uint256 i = 0; i < data.length; i++) {
            results[i] = Address.functionDelegateCall(address(this), data[i]);
        }
        return results;
    }
}

// File: contracts/interfaces/hooks/base/IHook.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

/// @notice Enum for representing various states of an async hook.
enum HookResult {
    Pending, // Indicates the hook is ongoing execution.
    Completed // Indicates the hook has successfully completed.
}

/// @title Hook Interface.
/// @notice This interface defines methods for synchronous and asynchronous hooks.
/// @dev Hooks are used to execute custom logic in response to certain events or conditions.
interface IHook {
    /// @notice Executes a synchronous hook.
    /// @param hookContext_ The context of an executing hook. It is an encoded version of Hook.ExecutionContext
    /// @return result The result of the hook execution.
    /// @return hookData The data returned by the hook.
    function executeSync(bytes calldata hookContext_) external returns (HookResult result, bytes memory hookData);

    /// @notice Executes an asynchronous hook.
    /// @param hookContext_ The context of an executing hook. It is an encoded version of Hook.ExecutionContext
    /// @param callbackHandler_ The address of the callback handler.
    /// @return result The result of the hook execution.
    /// @return hookData The data returned by the hook.
    /// @return requestId The id of the request.
    function executeAsync(
        bytes calldata hookContext_,
        address callbackHandler_
    ) external returns (HookResult result, bytes memory hookData, bytes32 requestId);

    /// @notice Validates the configuration for the hook.
    /// @dev This should be overridden by hook implementations to provide custom validation logic.
    /// @param hookConfig_ The configuration data for the hook.
    function validateConfig(bytes calldata hookConfig_) external view;
}

// File: contracts/utils/FixedSet.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import { ShortString, ShortStrings } from "@openzeppelin/contracts/utils/ShortStrings.sol";

/// @title FixedSet Library
/// @notice Fork of OZ's set data structures library with the following changs:
/// - Values cannot be removed from the set for order preservation
/// - The library allows obtaining indexes of values
/// - Adds ShortString as a data type
library FixedSet {
    using ShortStrings for *;

    uint256 internal constant INDEX_NOT_FOUND = type(uint256).max;

    /// @notice Data structure for composing a fixed set.
    struct Set {
        // Array for storing values within the fixed set.
        bytes32[] _values;
        // One-based index of the set value (0 is a sentinel valu).
        mapping(bytes32 => uint256) _indexes;
    }

    /// @dev Adds a value to a set.
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // Value is stored at values.length due to one-indexing.
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /// @dev Checks whether a value is contained in the set.
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }

    /// @dev Returns the length of the set.
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /// @dev Returns the index of a value within the set.
    function _indexOf(Set storage set, bytes32 value) private view returns (uint256) {
        uint256 index = set._indexes[value];
        return index == 0 ? INDEX_NOT_FOUND : index - 1;
    }

    /// @dev Returns the value stored at the one-indexed positioned within the set.
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /// @dev Returns the entire fixed set as a bytes32-array.
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    ////////////////////////////////////////////////////////////////////////////
    //                            Bytes32Set                                  //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice Struct for composing fixed sets of bytes32 objects.
    struct Bytes32Set {
        Set _inner;
    }

    /// @dev Adds a value to the bytes32 set.
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /// @dev Checks whether a bytes32 set contains a value.
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /// @dev Gets the length of the bytes32 set.
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /// @dev Gets the value stored at the one-indexed position within the set.
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /// @dev Returns the one-indexed position of the value within the set.
    function indexOf(Bytes32Set storage set, bytes32 value) internal view returns (uint256) {
        return _indexOf(set._inner, value);
    }

    /// @dev Returns the entire set of bytes32 objects as an array.
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    ////////////////////////////////////////////////////////////////////////////
    //                            ShortStringSet                               //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice Fixed set data structure for representing SortStrings.
    struct ShortStringSet {
        Set _inner;
    }

    /// @dev Adds a value to the ShortString data set.
    function add(ShortStringSet storage set, ShortString value) internal returns (bool) {
        return _add(set._inner, ShortString.unwrap(value));
    }

    /// @dev Checks whether a ShortString set contains a value.
    function contains(ShortStringSet storage set, ShortString value) internal view returns (bool) {
        return _contains(set._inner, ShortString.unwrap(value));
    }

    /// @dev Returns the length of the ShortString set.
    function length(ShortStringSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /// @dev Returns the value stored at the one-indexed position in the set.
    function at(ShortStringSet storage set, uint256 index) internal view returns (ShortString) {
        return ShortString.wrap(_at(set._inner, index));
    }

    /// @dev Returns the index of the value within the ShortString set.
    function indexOf(ShortStringSet storage set, ShortString value) internal view returns (uint256) {
        return _indexOf(set._inner, ShortString.unwrap(value));
    }

    /// @dev Returns the entire ShortString data set.
    function values(ShortStringSet storage set) internal view returns (ShortString[] memory) {
        bytes32[] memory store = _values(set._inner);
        ShortString[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    ////////////////////////////////////////////////////////////////////////////
    //                            AddressSet                                  //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice Fixed set data structure for representing addresses.
    struct AddressSet {
        Set _inner;
    }

    /// @dev Adds a value to the fixed address set.
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /// @dev Checks whether a fixed address set contains a value.
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /// @dev Returns the length of the fixed address set.
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /// @dev Returns the value stored at the one-indexed position in the set.
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /// @dev Gets the index of an address within the fixed set.
    function indexOf(AddressSet storage set, address value) internal view returns (uint256) {
        return _indexOf(set._inner, bytes32(uint256(uint160(value))));
    }

    /// @dev Returns the entire suite of addresses stored in the set.
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    ////////////////////////////////////////////////////////////////////////////
    //                            UintSet                                     //
    ////////////////////////////////////////////////////////////////////////////

    /// @notice Fixed set data structure for storing uint256 numbers.
    struct UintSet {
        Set _inner;
    }

    /// @dev Adds a uint256 value into the fixed set.
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /// @dev Checks whether the fixed set contains a uint256 value.
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /// @dev Returns the length of the uint256 set.
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /// @dev Returns the value stored at a one-indexed position within the set.
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /// @dev Returns the index of a uint256 value within the set.
    function indexOf(UintSet storage set, uint256 value) internal view returns (uint256) {
        return _indexOf(set._inner, bytes32(value));
    }

    /// @dev Returns the entire suite of uint256 values within the set.
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

// File: node_modules/@openzeppelin/contracts/token/ERC721/IERC721.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

// File: node_modules/@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.0;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

// File: node_modules/@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

// File: node_modules/@openzeppelin/contracts/utils/Address.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

// File: node_modules/@openzeppelin/contracts/utils/Context.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

// File: node_modules/@openzeppelin/contracts/utils/introspection/ERC165.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

// File: node_modules/@openzeppelin/contracts/utils/math/Math.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

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

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

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @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.
     */
    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, "Math: 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;
        }
    }

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

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
        }
    }
}

// File: node_modules/@openzeppelin/contracts/utils/math/SignedMath.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

// File: node_modules/@openzeppelin/contracts/utils/StorageSlot.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.0;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
 * _Available since v4.9 for `string`, `bytes`._
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
}

// File: node_modules/@openzeppelin/contracts-upgradeable/utils/introspection/ERC165CheckerUpgradeable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/introspection/ERC165Checker.sol)

pragma solidity ^0.8.0;

import "./IERC165Upgradeable.sol";

/**
 * @dev Library used to query support of an interface declared via {IERC165}.
 *
 * Note that these functions return the actual result of the query: they do not
 * `revert` if an interface is not supported. It is up to the caller to decide
 * what to do in these cases.
 */
library ERC165CheckerUpgradeable {
    // As per the EIP-165 spec, no interface should ever match 0xffffffff
    bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;

    /**
     * @dev Returns true if `account` supports the {IERC165} interface.
     */
    function supportsERC165(address account) internal view returns (bool) {
        // Any contract that implements ERC165 must explicitly indicate support of
        // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
        return
            supportsERC165InterfaceUnchecked(account, type(IERC165Upgradeable).interfaceId) &&
            !supportsERC165InterfaceUnchecked(account, _INTERFACE_ID_INVALID);
    }

    /**
     * @dev Returns true if `account` supports the interface defined by
     * `interfaceId`. Support for {IERC165} itself is queried automatically.
     *
     * See {IERC165-supportsInterface}.
     */
    function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
        // query support of both ERC165 as per the spec and support of _interfaceId
        return supportsERC165(account) && supportsERC165InterfaceUnchecked(account, interfaceId);
    }

    /**
     * @dev Returns a boolean array where each value corresponds to the
     * interfaces passed in and whether they're supported or not. This allows
     * you to batch check interfaces for a contract where your expectation
     * is that some interfaces may not be supported.
     *
     * See {IERC165-supportsInterface}.
     *
     * _Available since v3.4._
     */
    function getSupportedInterfaces(
        address account,
        bytes4[] memory interfaceIds
    ) internal view returns (bool[] memory) {
        // an array of booleans corresponding to interfaceIds and whether they're supported or not
        bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);

        // query support of ERC165 itself
        if (supportsERC165(account)) {
            // query support of each interface in interfaceIds
            for (uint256 i = 0; i < interfaceIds.length; i++) {
                interfaceIdsSupported[i] = supportsERC165InterfaceUnchecked(account, interfaceIds[i]);
            }
        }

        return interfaceIdsSupported;
    }

    /**
     * @dev Returns true if `account` supports all the interfaces defined in
     * `interfaceIds`. Support for {IERC165} itself is queried automatically.
     *
     * Batch-querying can lead to gas savings by skipping repeated checks for
     * {IERC165} support.
     *
     * See {IERC165-supportsInterface}.
     */
    function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
        // query support of ERC165 itself
        if (!supportsERC165(account)) {
            return false;
        }

        // query support of each interface in interfaceIds
        for (uint256 i = 0; i < interfaceIds.length; i++) {
            if (!supportsERC165InterfaceUnchecked(account, interfaceIds[i])) {
                return false;
            }
        }

        // all interfaces supported
        return true;
    }

    /**
     * @notice Query if a contract implements an interface, does not check ERC165 support
     * @param account The address of the contract to query for support of an interface
     * @param interfaceId The interface identifier, as specified in ERC-165
     * @return true if the contract at account indicates support of the interface with
     * identifier interfaceId, false otherwise
     * @dev Assumes that account contains a contract that supports ERC165, otherwise
     * the behavior of this method is undefined. This precondition can be checked
     * with {supportsERC165}.
     *
     * Some precompiled contracts will falsely indicate support for a given interface, so caution
     * should be exercised when using this function.
     *
     * Interface identification is specified in ERC-165.
     */
    function supportsERC165InterfaceUnchecked(address account, bytes4 interfaceId) internal view returns (bool) {
        // prepare call
        bytes memory encodedParams = abi.encodeWithSelector(IERC165Upgradeable.supportsInterface.selector, interfaceId);

        // perform static call
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly {
            success := staticcall(30000, account, add(encodedParams, 0x20), mload(encodedParams), 0x00, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0x00)
        }

        return success && returnSize >= 0x20 && returnValue > 0;
    }
}

// File: node_modules/@openzeppelin/contracts/access/IAccessControl.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControl {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) external;
}

// File: contracts/interfaces/access-control/IAccessControlled.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

/// @title Access Controlled Interface
/// @notice This interface must be implemented by all protocol components that require
///         to be authorized via the global Access Control Singleton contract. This
///         initially includes all modules and hooks contracts, but will later be
///         sunset in favor of central authorization via the module registry.
interface IAccessControlled {
    /// @notice Emits when the global Access Control Singleton contract is updated.
    /// @param accessControl Address of the protocol-wide Access Control singleton contract.
    event AccessControlUpdated(address indexed accessControl);

    /// @notice Sets the Access Control Singleton instance.
    /// @param accessControl_ address of the new instance of the Access Control Singleton.
    function setAccessControl(address accessControl_) external;
}

// File: node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @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 ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
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);
}

// File: node_modules/@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @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 ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165Upgradeable {
    /**
     * @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);
}