Skip to content
Verified contractExactMIT

PermissionedResolver

Address0xab75ef59f76c8fdb1807eab35a1939a3c8036a41
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.25

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.25+commit.b61c2a91
Language
solidity
Optimization
Yes, 1,000 runs
EVM version
shanghai
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,425,318
Creation transaction
0xf7b4befb0e…960ce6d070

41 files

lib/contracts-v2/contracts/src/resolver/PermissionedResolver.sol

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

import {IMulticallable} from "@ens/contracts/resolvers/IMulticallable.sol";
import {IABIResolver} from "@ens/contracts/resolvers/profiles/IABIResolver.sol";
import {IAddressResolver} from "@ens/contracts/resolvers/profiles/IAddressResolver.sol";
import {IAddrResolver} from "@ens/contracts/resolvers/profiles/IAddrResolver.sol";
import {IContentHashResolver} from "@ens/contracts/resolvers/profiles/IContentHashResolver.sol";
import {IDataResolver} from "@ens/contracts/resolvers/profiles/IDataResolver.sol";
import {IExtendedResolver} from "@ens/contracts/resolvers/profiles/IExtendedResolver.sol";
import {IHasAddressResolver} from "@ens/contracts/resolvers/profiles/IHasAddressResolver.sol";
import {IInterfaceResolver} from "@ens/contracts/resolvers/profiles/IInterfaceResolver.sol";
import {INameResolver} from "@ens/contracts/resolvers/profiles/INameResolver.sol";
import {IPubkeyResolver} from "@ens/contracts/resolvers/profiles/IPubkeyResolver.sol";
import {ITextResolver} from "@ens/contracts/resolvers/profiles/ITextResolver.sol";
import {IVersionableResolver} from "@ens/contracts/resolvers/profiles/IVersionableResolver.sol";
import {ResolverFeatures} from "@ens/contracts/resolvers/ResolverFeatures.sol";
import {ENSIP19, COIN_TYPE_ETH, COIN_TYPE_DEFAULT} from "@ens/contracts/utils/ENSIP19.sol";
import {IERC7996} from "@ens/contracts/utils/IERC7996.sol";
import {LibMem} from "@ens/contracts/utils/LibMem/LibMem.sol";
import {NameCoder} from "@ens/contracts/utils/NameCoder.sol";
import {IProxyAuthorization} from "@ensdomains/verifiable-factory/IProxyAuthorization.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {ERC165Checker} from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";

import {EnhancedAccessControl} from "../access-control/EnhancedAccessControl.sol";
import {IEnhancedAccessControl} from "../access-control/interfaces/IEnhancedAccessControl.sol";
import {IContractNamer} from "../reverse-registrar/interfaces/IContractNamer.sol";

import {IPermissionedResolver} from "./interfaces/IPermissionedResolver.sol";
import {PermissionedResolverLib} from "./libraries/PermissionedResolverLib.sol";
import {ResolverProfileRewriterLib} from "./libraries/ResolverProfileRewriterLib.sol";

/// @notice A resolver that supports many profiles, multiple names, internal aliasing, and fine-grained permissions.
///
/// Supported profiles and standards:
///
/// - ENSIP-1 / EIP-137: addr()
/// - ENSIP-3 / EIP-181: name()
/// - ENSIP-4 / EIP-205: ABI()
/// - EIP-619: pubkey()
/// - ENSIP-5 / EIP-634: text(key)
/// - ENSIP-7 / EIP-1577: contenthash()
/// - ENSIP-8: interfaceImplementer()
/// - ENSIP-9 / EIP-2304: addr(coinType)
/// - ENSIP-19: addr(default)
/// - ENSIP-24: data(key)
/// - IERC7996: supportsFeature()
/// - IVersionableResolver: version()
/// - IHasAddrResolver: hasAddr()
///
/// Internal Aliasing:
///
/// * Resolved names find the longest match and rewrite the suffix.
/// * Successful matches recursively check for additional aliasing.
/// * `bytes32 node` in calldata is updated accordingly.
/// * Cycles of length 1 apply once.
/// * Cycles of length 2+ result in OOG.
///
/// eg. `setAlias("a.eth", "b.eth")`
/// * `getAlias("a.eth") => "b.eth"`
/// * `getAlias("[sub].a.eth") => "[sub].b.eth"`
/// * `getAlias("[x.y].a.eth") => "[x.y].b.eth"`
/// * `getAlias("abc.eth") => ""`
///
/// Fine-grained Permissions:
///
/// * `setText(key)` can be permissioned with `authorizeTextRoles()`
///    - caller requires `ROLE_SET_TEXT_ADMIN` on `resource(<namehash>, 0)`
///    - `ROLE_SET_TEXT` is authorized on `resource(<namehash>, <part>)`
/// * `setData(key)` can be permissioned with `authorizeDataRoles()`
///    - caller requires `ROLE_SET_DATA_ADMIN` on `resource(<namehash>, 0)`
///    - `ROLE_SET_DATA` is authorized on `resource(<namehash>, <part>)`
/// * `setAddr(coinType)` can be permissioned with `authorizeAddrRoles()`
///    - caller requires `ROLE_SET_ADDR_ADMIN` on `resource(<namehash>, 0)`
///    - `ROLE_SET_ADDR` is authorized on `resource(<namehash>, <part>)`
///
/// Setters with `node` check (4) EAC resources:
///                                           Parts
///        Resources      +-----------------------------+------------------------------+
///                       |           Any (*)           |         Specific (1)         |
///        +--------------+-----------------------------+------------------------------+
///        |      Any (*) |       resource(0, 0)        |      resource(0, <part>)     |
///  Names |--------------+-----------------------------+------------------------------+
///        | Specific (1) |   resource(<namehash>, 0)   | resource(<namehash>, <part>) |
///        +--------------+-----------------------------+------------------------------+
///
contract PermissionedResolver is
    IPermissionedResolver,
    UUPSUpgradeable,
    EnhancedAccessControl,
    IERC7996,
    IMulticallable,
    IABIResolver,
    IAddrResolver,
    IAddressResolver,
    IContentHashResolver,
    IDataResolver,
    IHasAddressResolver,
    IInterfaceResolver,
    INameResolver,
    IPubkeyResolver,
    ITextResolver,
    IVersionableResolver,
    IProxyAuthorization,
    IContractNamer
{
    ////////////////////////////////////////////////////////////////////////
    // Types
    ////////////////////////////////////////////////////////////////////////

    struct Record {
        bytes contenthash;
        bytes32[2] pubkey;
        string name;
        mapping(uint256 coinType => bytes addressBytes) addresses;
        mapping(string key => string value) texts;
        mapping(string key => bytes value) datas;
        mapping(uint256 contentType => bytes value) abis;
        mapping(bytes4 interfaceId => address implementer) interfaces;
    }

    ////////////////////////////////////////////////////////////////////////
    // Storage
    ////////////////////////////////////////////////////////////////////////

    /// @dev Aliases for names.
    mapping(bytes32 node => bytes name) internal _aliases;

    /// @dev Versions for nodes.
    mapping(bytes32 node => uint64 version) internal _versions;

    /// @dev Records for nodes.
    mapping(bytes32 node => mapping(uint64 version => Record)) internal _records;

    ////////////////////////////////////////////////////////////////////////
    // Events
    ////////////////////////////////////////////////////////////////////////

    /// @notice Associate an EAC resource with a name.
    /// @param resource The EAC resource.
    /// @param name The name.
    event NamedResource(uint256 indexed resource, bytes name);

    /// @notice Associate an EAC resource with a name and specific `text(key)` record.
    /// @param resource The EAC resource.
    /// @param name The name.
    /// @param keyHash The hash of the key.
    /// @param key The key.
    event NamedTextResource(
        uint256 indexed resource,
        bytes name,
        bytes32 indexed keyHash,
        string key
    );

    /// @notice Associate an EAC resource with a name and specific `data(key)` record.
    /// @param resource The EAC resource.
    /// @param name The name.
    /// @param keyHash The hash of the key.
    /// @param key The key.
    event NamedDataResource(
        uint256 indexed resource,
        bytes name,
        bytes32 indexed keyHash,
        string key
    );

    /// @notice Associate an EAC resource with a name and specific `addr(coinType)` record.
    /// @param resource The EAC resource.
    /// @param name The name.
    /// @param coinType The coin type.
    event NamedAddrResource(uint256 indexed resource, bytes name, uint256 indexed coinType);

    ////////////////////////////////////////////////////////////////////////
    // Modifiers
    ////////////////////////////////////////////////////////////////////////

    modifier onlyPartRoles(bytes32 node, bytes32 part, uint256 roleBitmap) {
        if (
            part == bytes32(0) ||
            (!hasRoles(PermissionedResolverLib.resource(node, part), roleBitmap, msg.sender) &&
                !hasRoles(PermissionedResolverLib.resource(0, part), roleBitmap, msg.sender))
        ) {
            _checkRoles(PermissionedResolverLib.resource(node, 0), roleBitmap, msg.sender); // reverts using "widest" resource
        }
        _;
    }

    ////////////////////////////////////////////////////////////////////////
    // Initialization
    ////////////////////////////////////////////////////////////////////////

    /// @param namer The implementation namer.
    constructor(address namer) {
        _grantRoles(
            ROOT_RESOURCE,
            PermissionedResolverLib.ROLE_CAN_NAME | PermissionedResolverLib.ROLE_CAN_NAME_ADMIN,
            namer,
            false
        );
        _disableInitializers();
    }

    /// @inheritdoc EnhancedAccessControl
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return
            type(IPermissionedResolver).interfaceId == interfaceId ||
            type(IExtendedResolver).interfaceId == interfaceId ||
            type(IERC7996).interfaceId == interfaceId ||
            type(IMulticallable).interfaceId == interfaceId ||
            type(IABIResolver).interfaceId == interfaceId ||
            type(IAddrResolver).interfaceId == interfaceId ||
            type(IAddressResolver).interfaceId == interfaceId ||
            type(IContentHashResolver).interfaceId == interfaceId ||
            type(IDataResolver).interfaceId == interfaceId ||
            type(IHasAddressResolver).interfaceId == interfaceId ||
            type(IInterfaceResolver).interfaceId == interfaceId ||
            type(INameResolver).interfaceId == interfaceId ||
            type(IPubkeyResolver).interfaceId == interfaceId ||
            type(ITextResolver).interfaceId == interfaceId ||
            type(IVersionableResolver).interfaceId == interfaceId ||
            type(UUPSUpgradeable).interfaceId == interfaceId ||
            type(IProxyAuthorization).interfaceId == interfaceId ||
            type(IContractNamer).interfaceId == interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /// @inheritdoc IERC7996
    function supportsFeature(bytes4 feature) external pure returns (bool) {
        return ResolverFeatures.RESOLVE_MULTICALL == feature;
    }

    /// @inheritdoc IPermissionedResolver
    function initialize(address admin, uint256 roleBitmap, bytes[] calldata setters)
        external
        initializer
    {
        __UUPSUpgradeable_init();
        _grantRoles(ROOT_RESOURCE, roleBitmap, admin, false);
        multicall(setters);
    }

    ////////////////////////////////////////////////////////////////////////
    // Implementation
    ////////////////////////////////////////////////////////////////////////

    /// @notice Clear all records for `node`.
    /// @param node The node to update.
    function clearRecords(bytes32 node)
        external
        onlyPartRoles(node, 0, PermissionedResolverLib.ROLE_CLEAR)
    {
        uint64 version = ++_versions[node];
        emit VersionChanged(node, version);
    }

    /// @inheritdoc IPermissionedResolver
    function setAlias(bytes calldata fromName, bytes calldata toName)
        external
        onlyRootRoles(PermissionedResolverLib.ROLE_SET_ALIAS)
    {
        _aliases[NameCoder.namehash(fromName, 0)] = toName;
        emit AliasChanged(fromName, toName, fromName, toName);
    }

    /// @notice Authorize `roleBitmap` permissions to `account` for `toName`.
    ///         Use `NameCoder.encode("")` for any name, which is equivalent to `grantRootRoles()`.
    /// @param toName The name to authorize roles for.
    /// @param roleBitmap The roles to authorize.
    /// @param account The account to authorize roles to.
    /// @param grant If `true`, grants, otherwise, revokes.
    /// @return success Whether the roles were updated.
    function authorizeNameRoles(
        bytes calldata toName,
        uint256 roleBitmap,
        address account,
        bool grant
    )
        external
        returns (bool)
    {
        bytes32 node = NameCoder.namehash(toName, 0);
        uint256 resource = PermissionedResolverLib.resource(node, 0);
        if (grant) {
            _checkCanGrantRoles(resource, roleBitmap, msg.sender);
            if (resource != ROOT_RESOURCE && roleCount(resource) == 0) {
                emit NamedResource(resource, toName);
            }
            return _grantRoles(resource, roleBitmap, account, true);
        } else {
            _checkCanRevokeRoles(resource, roleBitmap, msg.sender);
            return _revokeRoles(resource, roleBitmap, account, true);
        }
    }

    /// @notice Authorize `setText(key)` permission to `account` for `toName`.
    ///         Use `NameCoder.encode("")` for any name.
    /// @param toName The name to authorize roles for.
    /// @param key The text key to authorize roles for.
    /// @param account The account to authorize roles to.
    /// @param grant If `true`, grants, otherwise, revokes.
    /// @return `true` if the roles were updated.
    function authorizeTextRoles(
        bytes calldata toName,
        string calldata key,
        address account,
        bool grant
    )
        external
        returns (bool)
    {
        bytes32 node = NameCoder.namehash(toName, 0);
        uint256 roleBit = PermissionedResolverLib.ROLE_SET_TEXT;
        uint256 nodeResource = PermissionedResolverLib.resource(node, bytes32(0));
        uint256 partResource =
            PermissionedResolverLib.resource(node, PermissionedResolverLib.partHash(key));
        if (grant) {
            _checkCanGrantRoles(nodeResource, roleBit, msg.sender);
            if (roleCount(partResource) == 0) {
                emit NamedTextResource(partResource, toName, keccak256(bytes(key)), key);
            }
            return _grantRoles(partResource, roleBit, account, true);
        } else {
            _checkCanRevokeRoles(nodeResource, roleBit, msg.sender);
            return _revokeRoles(partResource, roleBit, account, true);
        }
    }

    /// @notice Authorize `setData(key)` permission to `account` for `toName`.
    ///         Use `NameCoder.encode("")` for any name.
    /// @param toName The name to authorize roles for.
    /// @param key The data key to authorize roles for.
    /// @param account The account to authorize roles to.
    /// @param grant If `true`, grants, otherwise, revokes.
    /// @return `true` if the roles were updated.
    function authorizeDataRoles(
        bytes calldata toName,
        string calldata key,
        address account,
        bool grant
    )
        external
        returns (bool)
    {
        bytes32 node = NameCoder.namehash(toName, 0);
        uint256 roleBit = PermissionedResolverLib.ROLE_SET_DATA;
        uint256 nodeResource = PermissionedResolverLib.resource(node, bytes32(0));
        uint256 partResource =
            PermissionedResolverLib.resource(node, PermissionedResolverLib.partHash(key));
        if (grant) {
            _checkCanGrantRoles(nodeResource, roleBit, msg.sender);
            if (roleCount(partResource) == 0) {
                emit NamedDataResource(partResource, toName, keccak256(bytes(key)), key);
            }
            return _grantRoles(partResource, roleBit, account, true);
        } else {
            _checkCanRevokeRoles(nodeResource, roleBit, msg.sender);
            return _revokeRoles(partResource, roleBit, account, true);
        }
    }

    /// @notice Authorize `setAddr(coinType)` permission to `account` for `toName`.
    ///         Use `NameCoder.encode("")` for any name.
    /// @param toName The name to authorize roles for.
    /// @param coinType The coin type to authorize roles for.
    /// @param account The account to authorize roles to.
    /// @param grant If `true`, grants, otherwise, revokes.
    /// @return updated `true` if the roles were updated.
    function authorizeAddrRoles(bytes calldata toName, uint256 coinType, address account, bool grant)
        external
        returns (bool updated)
    {
        bytes32 node = NameCoder.namehash(toName, 0);
        uint256 roleBit = PermissionedResolverLib.ROLE_SET_ADDR;
        uint256 nodeResource = PermissionedResolverLib.resource(node, bytes32(0));
        uint256 partResource =
            PermissionedResolverLib.resource(node, PermissionedResolverLib.partHash(coinType));
        if (grant) {
            _checkCanGrantRoles(nodeResource, roleBit, msg.sender);
            if (roleCount(partResource) == 0) {
                emit NamedAddrResource(partResource, toName, coinType);
            }
            return _grantRoles(partResource, roleBit, account, true);
        } else {
            _checkCanRevokeRoles(nodeResource, roleBit, msg.sender);
            return _revokeRoles(partResource, roleBit, account, true);
        }
    }

    /// @notice Set ABI data of the associated ENS node.
    /// @param node The node to update.
    /// @param contentType The content type of the ABI.
    /// @param value The ABI data.
    function setABI(bytes32 node, uint256 contentType, bytes calldata value)
        external
        onlyPartRoles(node, 0, PermissionedResolverLib.ROLE_SET_ABI)
    {
        if (!_isPowerOf2(contentType)) {
            revert InvalidContentType(contentType);
        }
        _record(node).abis[contentType] = value;
        emit ABIChanged(node, contentType);
    }

    /// @notice Set Ethereum mainnet address of the associated ENS node.
    ///         `address(0)` is stored as `new bytes(20)`.
    /// @param node The node to update.
    /// @param addr_ The mainnet address.
    function setAddr(bytes32 node, address addr_) external {
        setAddr(node, COIN_TYPE_ETH, abi.encodePacked(addr_));
    }

    /// @notice Set the contenthash of the associated ENS node.
    /// @param node The node to update.
    /// @param hash The contenthash to set.
    function setContenthash(bytes32 node, bytes calldata hash)
        external
        onlyPartRoles(node, 0, PermissionedResolverLib.ROLE_SET_CONTENTHASH)
    {
        _record(node).contenthash = hash;
        emit ContenthashChanged(node, hash);
    }

    /// @notice Set the data for `key` of the associated ENS node.
    /// @param node The node to update.
    /// @param key The data key.
    /// @param value The data value.
    function setData(bytes32 node, string calldata key, bytes calldata value)
        external
        onlyPartRoles(
            node,
            PermissionedResolverLib.partHash(key),
            PermissionedResolverLib.ROLE_SET_DATA
        )
    {
        _record(node).datas[key] = value;
        emit DataChanged(node, key, key, value);
    }

    /// @notice Set an interface of the associated ENS node.
    /// @param node The node to update.
    /// @param interfaceId The EIP-165 interface ID.
    /// @param implementer The address of the contract that implements this interface for this node.
    function setInterface(bytes32 node, bytes4 interfaceId, address implementer)
        external
        onlyPartRoles(node, 0, PermissionedResolverLib.ROLE_SET_INTERFACE)
    {
        _record(node).interfaces[interfaceId] = implementer;
        emit InterfaceChanged(node, interfaceId, implementer);
    }

    /// @notice Set the SECP256k1 public key associated with an ENS node.
    /// @param node The node to update.
    /// @param x The x coordinate of the public key.
    /// @param y The y coordinate of the public key.
    function setPubkey(bytes32 node, bytes32 x, bytes32 y)
        external
        onlyPartRoles(node, 0, PermissionedResolverLib.ROLE_SET_PUBKEY)
    {
        _record(node).pubkey = [x, y];
        emit PubkeyChanged(node, x, y);
    }

    /// @notice Set the name of the associated ENS node.
    /// @param node The node to update.
    /// @param primary The primary name.
    function setName(bytes32 node, string calldata primary)
        external
        onlyPartRoles(node, 0, PermissionedResolverLib.ROLE_SET_NAME)
    {
        _record(node).name = primary;
        emit NameChanged(node, primary);
    }

    /// @notice Set the text for `key` of the associated ENS node.
    /// @param node The node to update.
    /// @param key The text key.
    /// @param value The text value.
    function setText(bytes32 node, string calldata key, string calldata value)
        external
        onlyPartRoles(
            node,
            PermissionedResolverLib.partHash(key),
            PermissionedResolverLib.ROLE_SET_TEXT
        )
    {
        _record(node).texts[key] = value;
        emit TextChanged(node, key, key, value);
    }

    /// @notice Same as `multicall()`.
    /// @dev The node parameter is accepted for interface compatibility but is not used.
    ///      Permission checking is handled by individual function calls within the multicall.
    /// @param {node} Ignored, for interface compatibility.
    /// @param calls The calls to make.
    /// @return results The results of the calls.
    function multicallWithNodeCheck(
        bytes32 /* node */,
        bytes[] calldata calls
    )
        external
        returns (bytes[] memory)
    {
        return multicall(calls);
    }

    /// @inheritdoc IExtendedResolver
    function resolve(bytes calldata fromName, bytes calldata fromData)
        external
        view
        returns (bytes memory)
    {
        bytes memory toName = getAlias(fromName);
        bytes memory toData =
            ResolverProfileRewriterLib.replaceNode(
                fromData,
                NameCoder.namehash(toName.length == 0 ? fromName : toName, 0) // always rewrite node
            );
        if (bytes4(toData) == IMulticallable.multicall.selector) {
            // note: cannot staticcall multicall() because it reverts with first error
            assembly {
                mstore(add(toData, 4), sub(mload(toData), 4))
                toData := add(toData, 4) // drop selector
            }
            bytes[] memory m = abi.decode(toData, (bytes[]));
            for (uint256 i; i < m.length; ++i) {
                toData = m[i];
                (, bytes memory v) = address(this).staticcall(toData);
                if (v.length == 0) {
                    v = abi.encodeWithSelector(UnsupportedResolverProfile.selector, bytes4(toData));
                }
                m[i] = v;
            }
            return abi.encode(m);
        } else {
            (bool ok, bytes memory v) = address(this).staticcall(toData);
            if (!ok) {
                assembly {
                    revert(add(v, 32), mload(v))
                }
            } else if (v.length == 0) {
                revert UnsupportedResolverProfile(bytes4(fromData));
            }
            return v;
        }
    }

    /// @inheritdoc IContractNamer
    function isContractNamer(address namer) external view returns (bool) {
        return hasRootRoles(PermissionedResolverLib.ROLE_CAN_NAME, namer);
    }

    /// @notice Get the current version.
    /// @param node The node to check.
    /// @return version The current version.
    function recordVersions(bytes32 node) external view returns (uint64) {
        return _versions[node];
    }

    /// @inheritdoc IABIResolver
    function ABI(bytes32 node, uint256 contentTypes)
        external
        view
        returns (uint256 contentType, bytes memory value)
    {
        Record storage r = _record(node);
        for (contentType = 1; contentType > 0 && contentType <= contentTypes; contentType <<= 1) {
            if ((contentType & contentTypes) != 0) {
                value = r.abis[contentType];
                if (value.length > 0) {
                    return (contentType, value);
                }
            }
        }
        return (0, "");
    }

    /// @inheritdoc IHasAddressResolver
    function hasAddr(bytes32 node, uint256 coinType) external view returns (bool) {
        return _record(node).addresses[coinType].length > 0;
    }

    /// @inheritdoc IContentHashResolver
    function contenthash(bytes32 node) external view returns (bytes memory) {
        return _record(node).contenthash;
    }

    /// @inheritdoc IDataResolver
    function data(bytes32 node, string calldata key) external view returns (bytes memory) {
        return _record(node).datas[key];
    }

    /// @inheritdoc IInterfaceResolver
    function interfaceImplementer(bytes32 node, bytes4 interfaceId)
        external
        view
        returns (address implementer)
    {
        implementer = _record(node).interfaces[interfaceId];
        if (implementer == address(0)) {
            address pointer = addr(node);
            if (ERC165Checker.supportsInterface(pointer, interfaceId)) {
                implementer = pointer;
            }
        }
    }

    /// @inheritdoc INameResolver
    function name(bytes32 node) external view returns (string memory) {
        return _record(node).name;
    }

    /// @inheritdoc IPubkeyResolver
    function pubkey(bytes32 node) external view returns (bytes32 x, bytes32 y) {
        Record storage r = _record(node);
        x = r.pubkey[0];
        y = r.pubkey[1];
    }

    /// @inheritdoc ITextResolver
    function text(bytes32 node, string calldata key) external view returns (string memory) {
        return _record(node).texts[key];
    }

    /// @notice Declares this implementation as an eligible verifiable proxy upgrade target.
    /// @dev Upgrade authorization is still enforced by the current implementation during the UUPS
    ///      upgrade call.
    /// @param {previousImplementation} Ignored.
    /// @return allowed Always `true` for implementations in this resolver family.
    function canUpgradeFrom(
        address /* previousImplementation */
    )
        external
        pure
        virtual
        override
        returns (bool allowed)
    {
        return true;
    }

    /// @notice Perform multiple write operations.
    /// @dev Reverts with first error.
    /// @param calls The calls to make.
    /// @return results The results of the calls.
    function multicall(bytes[] calldata calls) public returns (bytes[] memory results) {
        results = new bytes[](calls.length);
        for (uint256 i; i < calls.length; ++i) {
            (bool ok, bytes memory v) = address(this).delegatecall(calls[i]);
            if (!ok) {
                assembly {
                    revert(add(v, 32), mload(v)) // propagate the first error
                }
            }
            results[i] = v;
        }
        return results;
    }

    /// @notice Set the address for `coinType` of the associated ENS node.
    ///         Reverts `InvalidEVMAddress` if coin type is EVM and not 0 or 20 bytes.
    /// @param node The node to update.
    /// @param coinType The coin type.
    /// @param addressBytes The encoded address.
    function setAddr(bytes32 node, uint256 coinType, bytes memory addressBytes)
        public
        onlyPartRoles(
            node,
            PermissionedResolverLib.partHash(coinType),
            PermissionedResolverLib.ROLE_SET_ADDR
        )
    {
        if (
            addressBytes.length != 0 && addressBytes.length != 20 && ENSIP19.isEVMCoinType(coinType)
        ) {
            revert InvalidEVMAddress(addressBytes);
        }
        _record(node).addresses[coinType] = addressBytes;
        emit AddressChanged(node, coinType, addressBytes);
        if (coinType == COIN_TYPE_ETH) {
            emit AddrChanged(node, address(bytes20(addressBytes)));
        }
    }

    /// @inheritdoc IAddressResolver
    function addr(bytes32 node, uint256 coinType) public view returns (bytes memory addressBytes) {
        Record storage r = _record(node);
        addressBytes = r.addresses[coinType];
        if (addressBytes.length == 0 && ENSIP19.chainFromCoinType(coinType) > 0) {
            addressBytes = r.addresses[COIN_TYPE_DEFAULT];
        }
    }

    /// @inheritdoc IAddrResolver
    function addr(bytes32 node) public view returns (address payable) {
        return payable(address(bytes20(addr(node, COIN_TYPE_ETH))));
    }

    /// @inheritdoc IPermissionedResolver
    function getAlias(bytes memory fromName) public view returns (bytes memory toName) {
        bytes32 prev;
        for (;;) {
            bytes memory matchName;
            (matchName, fromName) = _resolveAlias(fromName);
            if (fromName.length == 0)
                break; // no alias
            bytes32 next = keccak256(matchName);
            if (next == prev)
                break; // same alias
            toName = fromName;
            prev = next;
        }
    }

    /// @notice Function is disabled.  Use `authorize(Name|Text|Addr)Roles()` instead.
    /// @param resource Ignored.
    /// @param roleBitmap Ignored.
    /// @param account Ignored.
    /// @return success Ignored, always reverts.
    function grantRoles(uint256 resource, uint256 roleBitmap, address account)
        public
        pure
        override(EnhancedAccessControl, IEnhancedAccessControl)
        returns (bool)
    {
        revert EACCannotGrantRoles(resource, roleBitmap, account);
    }

    /// @notice Function is disabled.  Use `authorize(Name|Text|Addr)Roles()` instead.
    /// @param resource Ignored.
    /// @param roleBitmap Ignored.
    /// @param account Ignored.
    /// @return success Ignored, always reverts.
    function revokeRoles(uint256 resource, uint256 roleBitmap, address account)
        public
        pure
        override(EnhancedAccessControl, IEnhancedAccessControl)
        returns (bool)
    {
        revert EACCannotRevokeRoles(resource, roleBitmap, account);
    }

    ////////////////////////////////////////////////////////////////////////
    // Internal Functions
    ////////////////////////////////////////////////////////////////////////

    /// @dev Allow `ROLE_UPGRADE` to upgrade.
    function _authorizeUpgrade(address newImplementation)
        internal
        override
        onlyRootRoles(PermissionedResolverLib.ROLE_UPGRADE)
    {
        //
    }

    /// @dev Avoid permission checks during initialization.
    function _checkRoles(uint256 resource, uint256 roleBitmap, address account)
        internal
        view
        override
    {
        if (!_isInitializing()) {
            super._checkRoles(resource, roleBitmap, account);
        }
    }

    /// @dev Apply one round of aliasing.
    /// @param fromName The source DNS-encoded name.
    /// @return matchName The alias that matched.
    /// @return toName The destination DNS-encoded name or empty if no match.
    function _resolveAlias(bytes memory fromName)
        internal
        view
        returns (bytes memory matchName, bytes memory toName)
    {
        uint256 offset;
        while (offset < fromName.length) {
            matchName = _aliases[NameCoder.namehash(fromName, offset)];
            if (matchName.length > 0) {
                if (offset > 0) {
                    // rewrite prefix: [x.y].{fromName[offset:]} => [x.y].{matchName}
                    toName = new bytes(offset + matchName.length);
                    // hex-names: PulseChain has no MCOPY (Cancun), so copy with the ens-contracts
                    // LibMem loop instead. Same result: the two regions never overlap.
                    LibMem.copy(LibMem.ptr(toName), LibMem.ptr(fromName), offset); // copy prefix
                    LibMem.copy(LibMem.ptr(toName) + offset, LibMem.ptr(matchName), matchName.length); // copy suffix
                } else {
                    toName = matchName;
                }
                break;
            }
            (, offset) = NameCoder.nextLabel(fromName, offset);
        }
    }

    /// @dev Access record storage pointer.
    function _record(bytes32 node) internal view returns (Record storage) {
        return _records[node][_versions[node]];
    }

    /// @dev Returns true if `x` has a single bit set.
    function _isPowerOf2(uint256 x) internal pure returns (bool) {
        return x > 0 && (x - 1) & x == 0;
    }
}

lib/contracts-v2/contracts/lib/ens-contracts/contracts/resolvers/IMulticallable.sol

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

interface IMulticallable {
    function multicall(
        bytes[] calldata data
    ) external returns (bytes[] memory results);

    function multicallWithNodeCheck(
        bytes32,
        bytes[] calldata data
    ) external returns (bytes[] memory results);
}

lib/contracts-v2/contracts/lib/ens-contracts/contracts/resolvers/ResolverFeatures.sol

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

library ResolverFeatures {
    /// @notice Implements `resolve(multicall([...]))`.
    /// @dev Feature: `0x96b62db8`
    bytes4 constant RESOLVE_MULTICALL =
        bytes4(keccak256("eth.ens.resolver.extended.multicall"));

    /// @notice Returns the same records independent of name or node.
    /// @dev Feature: `0x86fb8da8`
    bytes4 constant SINGULAR = bytes4(keccak256("eth.ens.resolver.singular"));
}

lib/contracts-v2/contracts/lib/ens-contracts/contracts/resolvers/profiles/IABIResolver.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;

interface IABIResolver {
    event ABIChanged(bytes32 indexed node, uint256 indexed contentType);

    /// Returns the ABI associated with an ENS node.
    /// Defined in EIP205.
    /// @param node The ENS node to query
    /// @param contentTypes A bitwise OR of the ABI formats accepted by the caller.
    /// @return contentType The content type of the return value
    /// @return data The ABI data
    function ABI(
        bytes32 node,
        uint256 contentTypes
    ) external view returns (uint256, bytes memory);
}

lib/contracts-v2/contracts/lib/ens-contracts/contracts/resolvers/profiles/IAddrResolver.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;

/// Interface for the legacy (ETH-only) addr function.
interface IAddrResolver {
    event AddrChanged(bytes32 indexed node, address a);

    /// Returns the address associated with an ENS node.
    /// @param node The ENS node to query.
    /// @return The associated address.
    function addr(bytes32 node) external view returns (address payable);
}

lib/contracts-v2/contracts/lib/ens-contracts/contracts/resolvers/profiles/IAddressResolver.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;

/// Interface for the new (multicoin) addr function.
interface IAddressResolver {
    event AddressChanged(
        bytes32 indexed node,
        uint256 coinType,
        bytes newAddress
    );

    function addr(
        bytes32 node,
        uint256 coinType
    ) external view returns (bytes memory);
}

lib/contracts-v2/contracts/lib/ens-contracts/contracts/resolvers/profiles/IContentHashResolver.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;

interface IContentHashResolver {
    event ContenthashChanged(bytes32 indexed node, bytes hash);

    /// Returns the contenthash associated with an ENS node.
    /// @param node The ENS node to query.
    /// @return The associated contenthash.
    function contenthash(bytes32 node) external view returns (bytes memory);
}

lib/contracts-v2/contracts/lib/ens-contracts/contracts/resolvers/profiles/IDataResolver.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;

/// @dev Interface selector: `0xecbfada3`
interface IDataResolver {
    /// @notice For a specific `node`, the data associated with a `key` has changed.
    event DataChanged(
        bytes32 indexed node, 
        string indexed indexedKey,
        string key, 
        bytes indexed indexedData
    );
    
    /// @notice For a specific `node`, get the data associated with the key, `key`.
    /// @param node The node (namehash) for which data is being fetched.
    /// @param key The key.
    /// @return The associated arbitrary `bytes` data.
    function data(
        bytes32 node,
        string calldata key
    ) external view returns (bytes memory);
}

lib/contracts-v2/contracts/lib/ens-contracts/contracts/resolvers/profiles/IExtendedResolver.sol

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

interface IExtendedResolver {
    function resolve(
        bytes memory name,
        bytes memory data
    ) external view returns (bytes memory);
}

lib/contracts-v2/contracts/lib/ens-contracts/contracts/resolvers/profiles/IHasAddressResolver.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;

interface IHasAddressResolver {
    /// @notice Determine if an addresss is stored for the coin type of the associated ENS node.
    /// @param node The node to query.
    /// @param coinType The coin type.
    /// @return True if the associated address is not empty.
    function hasAddr(
        bytes32 node,
        uint256 coinType
    ) external view returns (bool);
}

lib/contracts-v2/contracts/lib/ens-contracts/contracts/resolvers/profiles/IInterfaceResolver.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;

interface IInterfaceResolver {
    event InterfaceChanged(
        bytes32 indexed node,
        bytes4 indexed interfaceID,
        address implementer
    );

    /// Returns the address of a contract that implements the specified interface for this name.
    /// If an implementer has not been set for this interfaceID and name, the resolver will query
    /// the contract at `addr()`. If `addr()` is set, a contract exists at that address, and that
    /// contract implements EIP165 and returns `true` for the specified interfaceID, its address
    /// will be returned.
    /// @param node The ENS node to query.
    /// @param interfaceID The EIP 165 interface ID to check for.
    /// @return The address that implements this interface, or 0 if the interface is unsupported.
    function interfaceImplementer(
        bytes32 node,
        bytes4 interfaceID
    ) external view returns (address);
}

lib/contracts-v2/contracts/lib/ens-contracts/contracts/resolvers/profiles/INameResolver.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;

interface INameResolver {
    event NameChanged(bytes32 indexed node, string name);

    /// Returns the name associated with an ENS node, for reverse records.
    /// Defined in EIP181.
    /// @param node The ENS node to query.
    /// @return The associated name.
    function name(bytes32 node) external view returns (string memory);
}

lib/contracts-v2/contracts/lib/ens-contracts/contracts/resolvers/profiles/IPubkeyResolver.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;

interface IPubkeyResolver {
    event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y);

    /// Returns the SECP256k1 public key associated with an ENS node.
    /// Defined in EIP 619.
    /// @param node The ENS node to query
    /// @return x The X coordinate of the curve point for the public key.
    /// @return y The Y coordinate of the curve point for the public key.
    function pubkey(bytes32 node) external view returns (bytes32 x, bytes32 y);
}

lib/contracts-v2/contracts/lib/ens-contracts/contracts/resolvers/profiles/ITextResolver.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;

interface ITextResolver {
    event TextChanged(
        bytes32 indexed node,
        string indexed indexedKey,
        string key,
        string value
    );

    /// Returns the text data associated with an ENS node and key.
    /// @param node The ENS node to query.
    /// @param key The text data key to query.
    /// @return The associated text data.
    function text(
        bytes32 node,
        string calldata key
    ) external view returns (string memory);
}

lib/contracts-v2/contracts/lib/ens-contracts/contracts/resolvers/profiles/IVersionableResolver.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;

interface IVersionableResolver {
    event VersionChanged(bytes32 indexed node, uint64 newVersion);

    function recordVersions(bytes32 node) external view returns (uint64);
}

lib/contracts-v2/contracts/lib/ens-contracts/contracts/utils/BytesUtils.sol

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

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

library BytesUtils {
    /// @dev `offset` was beyond `length`.
    ///       Error selector: `0x8a3c1cfb`
    error OffsetOutOfBoundsError(uint256 offset, uint256 length);

    /// @dev Assert `end` is not beyond the length of `v`.
    function _checkBound(bytes memory v, uint256 end) internal pure {
        if (end > v.length) {
            revert OffsetOutOfBoundsError(end, v.length);
        }
    }

    /// @dev Compute `keccak256(v[off:off+len])`.
    /// @param v The source bytes.
    /// @param off The offset into the source.
    /// @param len The number of bytes to hash.
    /// @return ret The corresponding hash.
    function keccak(
        bytes memory v,
        uint256 off,
        uint256 len
    ) internal pure returns (bytes32 ret) {
        _checkBound(v, off + len);
        assembly ("memory-safe") {
            ret := keccak256(add(add(v, 32), off), len)
        }
    }

    /// @dev Lexicographically compare two byte strings.
    /// @param vA The first bytes to compare.
    /// @param vB The second bytes to compare.
    /// @return Positive number if `A > B`, negative number if `A < B`, or zero if `A == B`.
    function compare(
        bytes memory vA,
        bytes memory vB
    ) internal pure returns (int256) {
        return compare(vA, 0, vA.length, vB, 0, vB.length);
    }

    /// @dev Lexicographically compare two byte ranges: `A = vA[offA:offA+lenA]` and `B = vB[offB:offB+lenB]`.
    /// @param vA The first bytes.
    /// @param offA The offset of the first bytes.
    /// @param lenA The length of the first bytes.
    /// @param vB The second bytes.
    /// @param offB The offset of the second bytes.
    /// @param lenB The length of the second bytes.
    /// @return Positive number if `A > B`, negative number if `A < B`, or zero if `A == B`.
    function compare(
        bytes memory vA,
        uint256 offA,
        uint256 lenA,
        bytes memory vB,
        uint256 offB,
        uint256 lenB
    ) internal pure returns (int256) {
        _checkBound(vA, offA + lenA);
        _checkBound(vB, offB + lenB);
        unchecked {
            uint256 ptrA = LibMem.ptr(vA) + offA;
            uint256 ptrB = LibMem.ptr(vB) + offB;
            uint256 shortest = lenA < lenB ? lenA : lenB;
            for (uint256 i; i < shortest; i += 32) {
                uint256 a = LibMem.load(ptrA + i);
                uint256 b = LibMem.load(ptrB + i);
                if (a != b) {
                    uint256 rest = shortest - i;
                    if (rest < 32) {
                        rest = (32 - rest) << 3; // bits to drop
                        a >>= rest; // shift out the
                        b >>= rest; // irrelevant bits
                    }
                    if (a < b) {
                        return -1;
                    } else if (a > b) {
                        return 1;
                    }
                }
            }
        }
        return int256(lenA) - int256(lenB);
    }

    /// @dev Determine if `a[offA:offA+len] == b[offB:offB+len]`.
    /// @param vA The first bytes.
    /// @param offA The offset into the first bytes.
    /// @param vB The second bytes.
    /// @param offB The offset into the second bytes.
    /// @param len The number of bytes to compare.
    /// @return True if the byte ranges are equal.
    function equals(
        bytes memory vA,
        uint256 offA,
        bytes memory vB,
        uint256 offB,
        uint256 len
    ) internal pure returns (bool) {
        return keccak(vA, offA, len) == keccak(vB, offB, len);
    }

    /// @dev Determine if `a[offA:] == b[offB:]`.
    /// @param vA The first bytes.
    /// @param offA The offset into the first bytes.
    /// @param vB The second bytes.
    /// @param offB The offset into the second bytes.
    /// @return True if the byte ranges are equal.
    function equals(
        bytes memory vA,
        uint256 offA,
        bytes memory vB,
        uint256 offB
    ) internal pure returns (bool) {
        _checkBound(vA, offA);
        _checkBound(vB, offB);
        unchecked {
            return
                keccak(vA, offA, vA.length - offA) ==
                keccak(vB, offB, vB.length - offB);
        }
    }

    /// @dev Determine if `a[offA:] == b`.
    /// @param vA The first bytes.
    /// @param offA The offset into the first bytes.
    /// @param vB The second bytes.
    /// @return True if the byte ranges are equal.
    function equals(
        bytes memory vA,
        uint256 offA,
        bytes memory vB
    ) internal pure returns (bool) {
        return
            vA.length == offA + vB.length &&
            keccak(vA, offA, vB.length) == keccak256(vB);
    }

    /// @dev Determine if `a == b`.
    /// @param vA The first bytes.
    /// @param vB The second bytes.
    /// @return True if the bytes are equal.
    function equals(
        bytes memory vA,
        bytes memory vB
    ) internal pure returns (bool) {
        return vA.length == vB.length && keccak256(vA) == keccak256(vB);
    }

    /// @dev Returns `uint8(v[off])`.
    /// @param v The source bytes.
    /// @param off The offset into the source.
    /// @return The corresponding `uint8`.
    function readUint8(
        bytes memory v,
        uint256 off
    ) internal pure returns (uint8) {
        _checkBound(v, off + 1);
        unchecked {
            return uint8(v[off]);
        }
    }

    /// @dev Returns `uint16(bytes2(v[off:off+2]))`.
    /// @param v The source bytes.
    /// @param off The offset into the source.
    /// @return ret The corresponding `uint16`.
    function readUint16(
        bytes memory v,
        uint256 off
    ) internal pure returns (uint16 ret) {
        _checkBound(v, off + 2);
        assembly ("memory-safe") {
            ret := shr(240, mload(add(add(v, 32), off)))
        }
    }

    /// @dev Returns `uint32(bytes4(v[off:off+4]))`.
    /// @param v The source bytes.
    /// @param off The offset into the source.
    /// @return ret The corresponding `uint32`.
    function readUint32(
        bytes memory v,
        uint256 off
    ) internal pure returns (uint32 ret) {
        _checkBound(v, off + 4);
        assembly ("memory-safe") {
            ret := shr(224, mload(add(add(v, 32), off)))
        }
    }

    /// @dev Returns `bytes20(v[off:off+20])`.
    /// @param v The source bytes.
    /// @param off The offset into the source.
    /// @return ret The corresponding `bytes20`.
    function readBytes20(
        bytes memory v,
        uint256 off
    ) internal pure returns (bytes20 ret) {
        _checkBound(v, off + 20);
        assembly ("memory-safe") {
            ret := shl(96, mload(add(add(v, 20), off)))
        }
    }

    /// @dev Returns `bytes32(v[off:off+32])`.
    /// @param v The source bytes.
    /// @param off The offset into the source.
    /// @return ret The corresponding `bytes32`.
    function readBytes32(
        bytes memory v,
        uint256 off
    ) internal pure returns (bytes32 ret) {
        _checkBound(v, off + 32);
        assembly ("memory-safe") {
            ret := mload(add(add(v, 32), off))
        }
    }

    /// @dev Returns `bytes32(bytesN(v[off:off+len]))`.
    ///      Accepts 0-32 bytes or reverts.
    /// @param v The source bytes.
    /// @param off The offset into the source.
    /// @param len The number of bytes.
    /// @return ret The corresponding N-bytes left-aligned in a `bytes32`.
    function readBytesN(
        bytes memory v,
        uint256 off,
        uint256 len
    ) internal pure returns (bytes32 ret) {
        assert(len <= 32);
        _checkBound(v, off + len);
        assembly ("memory-safe") {
            let mask := sub(shl(shl(3, sub(32, len)), 1), 1) // <(32-N)x00><NxFF>
            ret := and(mload(add(add(v, 32), off)), not(mask))
        }
    }

    /// @dev Copy `vSrc[offSrc:offSrc+len]` to `vDst[offDst:offDst:len]`.
    /// @param vSrc The source bytes.
    /// @param offSrc The offset into the source to begin the copy.
    /// @param vDst The destination bytes.
    /// @param offDst The offset into the destination to place the copy.
    /// @param len The number of bytes to copy.
    function copyBytes(
        bytes memory vSrc,
        uint256 offSrc,
        bytes memory vDst,
        uint256 offDst,
        uint256 len
    ) internal pure {
        _checkBound(vSrc, offSrc + len);
        _checkBound(vDst, offDst + len);
        unchecked {
            LibMem.copy(
                LibMem.ptr(vDst) + offDst,
                LibMem.ptr(vSrc) + offSrc,
                len
            );
        }
    }

    /// @dev Copies a substring into a new byte string.
    /// @param vSrc The byte string to copy from.
    /// @param off The offset to start copying at.
    /// @param len The number of bytes to copy.
    /// @return vDst The copied substring.
    function substring(
        bytes memory vSrc,
        uint256 off,
        uint256 len
    ) internal pure returns (bytes memory vDst) {
        vDst = new bytes(len);
        copyBytes(vSrc, off, vDst, 0, len);
    }

    /// @dev Find the first occurrence of `needle`.
    /// @param v The bytes to search.
    /// @param off The offset to start searching.
    /// @param len The number of bytes to search.
    /// @param needle The byte to search for.
    /// @return The offset of `needle`, or `type(uint256).max` if not found.
    function find(
        bytes memory v,
        uint256 off,
        uint256 len,
        bytes1 needle
    ) internal pure returns (uint256) {
        for (uint256 end = off + len; off < end; off++) {
            if (v[off] == needle) {
                return off;
            }
        }
        return type(uint256).max;
    }

    /// @dev Returns `true` if word contains a zero byte.
    function hasZeroByte(uint256 word) internal pure returns (bool) {
        unchecked {
            return
                ((~word &
                    (word -
                        0x0101010101010101010101010101010101010101010101010101010101010101)) &
                    0x8080808080808080808080808080808080808080808080808080808080808080) !=
                0;
        }
    }

    /// @dev Efficiently check if `v[off:off+len]` contains `needle` byte.
    /// @param v The source bytes.
    /// @param off The offset into the source.
    /// @param len The number of bytes to search.
    /// @param needle The byte to search for.
    /// @return found `true` if `needle` was found.
    function includes(
        bytes memory v,
        uint256 off,
        uint256 len,
        bytes1 needle
    ) internal pure returns (bool found) {
        _checkBound(v, off + len);
        unchecked {
            uint256 wide = uint8(needle);
            wide |= wide << 8;
            wide |= wide << 16;
            wide |= wide << 32;
            wide |= wide << 64;
            wide |= wide << 128; // broadcast byte across word
            off += LibMem.ptr(v);
            len += off;
            while (off < len) {
                uint256 word = LibMem.load(off) ^ wide; // zero needle byte
                off += 32;
                if (hasZeroByte(word)) {
                    return
                        off <= len ||
                        hasZeroByte(
                            word | ((1 << ((off - len) << 3)) - 1) // recheck overflow by making it nonzero
                        );
                }
            }
        }
    }
}

lib/contracts-v2/contracts/lib/ens-contracts/contracts/utils/ENSIP19.sol

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

import {HexUtils} from "../utils/HexUtils.sol";
import {NameCoder} from "../utils/NameCoder.sol";

uint32 constant CHAIN_ID_ETH = 1;

uint256 constant COIN_TYPE_ETH = 60;
uint256 constant COIN_TYPE_DEFAULT = 1 << 31; // 0x8000_0000

string constant SLUG_ETH = "addr"; // <=> COIN_TYPE_ETH
string constant SLUG_DEFAULT = "default"; // <=> COIN_TYPE_DEFAULT
string constant TLD_REVERSE = "reverse";

/// @dev Library for generating reverse names according to ENSIP-19.
/// https://docs.ens.domains/ensip/19
library ENSIP19 {
    /// @dev The supplied address was `0x`.
    ///      Error selector: `0x7138356f`
    error EmptyAddress();

    /// @dev Extract Chain ID from `coinType`.
    /// @param coinType The coin type.
    /// @return The Chain ID or 0 if non-EVM Chain.
    function chainFromCoinType(
        uint256 coinType
    ) internal pure returns (uint32) {
        if (coinType == COIN_TYPE_ETH) return CHAIN_ID_ETH;
        coinType ^= COIN_TYPE_DEFAULT;
        return uint32(coinType < COIN_TYPE_DEFAULT ? coinType : 0);
    }

    /// @dev Determine if Coin Type is for an EVM address.
    /// @param coinType The coin type.
    /// @return True if coin type represents an EVM address.
    function isEVMCoinType(uint256 coinType) internal pure returns (bool) {
        return coinType == COIN_TYPE_DEFAULT || chainFromCoinType(coinType) > 0;
    }

    /// @dev Generate Reverse Name from Address + Coin Type.
    ///      Reverts `EmptyAddress` if `addressBytes` is `0x`.
    /// @param addressBytes The input address.
    /// @param coinType The coin type.
    /// @return The ENS reverse name, eg. `1234abcd.addr.reverse`.
    function reverseName(
        bytes memory addressBytes,
        uint256 coinType
    ) internal pure returns (string memory) {
        if (addressBytes.length == 0) {
            revert EmptyAddress();
        }
        return
            string(
                abi.encodePacked(
                    HexUtils.bytesToHex(addressBytes),
                    bytes1("."),
                    coinType == COIN_TYPE_ETH
                        ? SLUG_ETH
                        : coinType == COIN_TYPE_DEFAULT
                            ? SLUG_DEFAULT
                            : HexUtils.unpaddedUintToHex(coinType, true),
                    bytes1("."),
                    TLD_REVERSE
                )
            );
    }

    /// @dev Parse Reverse Name into Address + Coin Type.
    ///      Matches: `/^[0-9a-fA-F]+\.([0-9a-f]{1,64}|addr|default)\.reverse$/`.
    ///      Reverts `DNSDecodingFailed`.
    /// @param name The DNS-encoded name.
    /// @return addressBytes The address or empty if invalid.
    /// @return coinType The coin type.
    function parse(
        bytes memory name
    ) internal pure returns (bytes memory addressBytes, uint256 coinType) {
        (, uint256 offset) = NameCoder.readLabel(name, 0);
        bool valid;
        (addressBytes, valid) = HexUtils.hexToBytes(name, 1, offset);
        if (!valid || addressBytes.length == 0) return ("", 0); // addressBytes not 1+ hex
        (valid, coinType) = parseNamespace(name, offset);
        if (!valid) return ("", 0); // invalid namespace
    }

    /// @dev Parse Reverse Namespace into Coin Type.
    ///      Matches: `/^([0-9a-f]{1,64}|addr|default)\.reverse$/`.
    ///      Reverts `DNSDecodingFailed`.
    /// @param name The DNS-encoded name.
    /// @param offset The offset to begin parsing.
    /// @return valid True if a valid reverse namespace.
    /// @return coinType The coin type.
    function parseNamespace(
        bytes memory name,
        uint256 offset
    ) internal pure returns (bool valid, uint256 coinType) {
        (bytes32 labelHash, uint256 offsetTLD) = NameCoder.readLabel(
            name,
            offset
        );
        if (labelHash == keccak256(bytes(SLUG_ETH))) {
            coinType = COIN_TYPE_ETH;
        } else if (labelHash == keccak256(bytes(SLUG_DEFAULT))) {
            coinType = COIN_TYPE_DEFAULT;
        } else if (labelHash == bytes32(0)) {
            return (false, 0); // no slug
        } else {
            (bytes32 word, bool validHex) = HexUtils.hexStringToBytes32(
                name,
                1 + offset,
                offsetTLD
            );
            if (!validHex) return (false, 0); // invalid coinType or too long
            coinType = uint256(word);
        }
        (labelHash, offset) = NameCoder.readLabel(name, offsetTLD);
        if (labelHash != keccak256(bytes(TLD_REVERSE))) return (false, 0); // invalid tld
        (labelHash, ) = NameCoder.readLabel(name, offset);
        if (labelHash != bytes32(0)) return (false, 0); // not tld
        valid = true;
    }
}

lib/contracts-v2/contracts/lib/ens-contracts/contracts/utils/HexUtils.sol

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

library HexUtils {
    /// @dev Convert `hexString[off:end]` to `bytes32`.
    ///      Accepts 0-64 hex-chars.
    ///      Uses right alignment: `1` &rarr; `0000000000000000000000000000000000000000000000000000000000000001`.
    /// @param hexString The string to parse.
    /// @param off The index to start parsing.
    /// @param end The (exclusive) index to stop parsing.
    /// @return word The parsed bytes32.
    /// @return valid True if the parse was successful.
    function hexStringToBytes32(
        bytes memory hexString,
        uint256 off,
        uint256 end
    ) internal pure returns (bytes32 word, bool valid) {
        if (end < off) return ("", false); // invalid range
        uint256 nibbles = end - off;
        if (nibbles > 64 || end > hexString.length) {
            return (bytes32(0), false); // too large or out of bounds
        }
        uint256 src;
        assembly {
            src := add(add(hexString, 32), off)
        }
        valid = unsafeBytes(src, 0, nibbles);
        assembly {
            let pad := sub(32, shr(1, add(nibbles, 1))) // number of bytes
            word := shr(shl(3, pad), mload(0)) // right align
        }
    }

    /// @dev Convert `hexString[off:end]` to `address`.
    ///      Accepts exactly 40 hex-chars.
    /// @param hexString The string to parse.
    /// @param off The index to start parsing.
    /// @param end The (exclusive) index to stop parsing.
    /// @return addr The parsed address.
    /// @return valid True if the parse was successful.
    function hexToAddress(
        bytes memory hexString,
        uint256 off,
        uint256 end
    ) internal pure returns (address addr, bool valid) {
        if (off + 40 != end) return (address(0), false); // wrong length
        bytes32 word;
        (word, valid) = hexStringToBytes32(hexString, off, end);
        addr = address(uint160(uint256(word)));
    }

    /// @dev Convert `hexString[off:end]` to `bytes`.
    ///      Accepts 0+ hex-chars.
    /// @param hexString The string to parse.
    /// @param off The index to start parsing.
    /// @param end The (exclusive) index to stop parsing.
    /// @return v The parsed bytes.
    /// @return valid True if the parse was successful.
    function hexToBytes(
        bytes memory hexString,
        uint256 off,
        uint256 end
    ) internal pure returns (bytes memory v, bool valid) {
        if (end < off) return ("", false); // invalid range
        uint256 nibbles = end - off;
        v = new bytes((1 + nibbles) >> 1); // round up
        uint256 src;
        uint256 dst;
        assembly {
            src := add(add(hexString, 32), off)
            dst := add(v, 32)
        }
        valid = unsafeBytes(src, dst, nibbles);
    }

    /// @dev Convert arbitrary hex-encoded memory to bytes.
    ///      If nibbles is odd, leading hex-char is padded, eg. `F` &rarr; `0x0F`.
    ///      Matches: `/^[0-9a-f]*$/i`.
    /// @param src The memory offset of first hex-char of input.
    /// @param dst The memory offset of first byte of output (cannot alias `src`).
    /// @param nibbles The number of hex-chars to convert.
    /// @return valid True if all characters were hex.
    function unsafeBytes(
        uint256 src,
        uint256 dst,
        uint256 nibbles
    ) internal pure returns (bool valid) {
        assembly {
            function getHex(c, i) -> ascii {
                c := byte(i, c)
                // chars 48-57: 0-9
                if and(gt(c, 47), lt(c, 58)) {
                    ascii := sub(c, 48)
                    leave
                }
                // chars 65-70: A-F
                if and(gt(c, 64), lt(c, 71)) {
                    ascii := add(sub(c, 65), 10)
                    leave
                }
                // chars 97-102: a-f
                if and(gt(c, 96), lt(c, 103)) {
                    ascii := add(sub(c, 97), 10)
                    leave
                }
                // invalid char
                ascii := 0x100
            }
            valid := true
            let end := add(src, nibbles)
            if and(nibbles, 1) {
                let b := getHex(mload(src), 0) // "f" -> 15
                mstore8(dst, b) // write ascii byte
                src := add(src, 1) // update pointers
                dst := add(dst, 1)
                if gt(b, 255) {
                    valid := false
                    src := end // terminate loop
                }
            }
            // prettier-ignore
            for {} lt(src, end) {
                src := add(src, 2) // 2 nibbles
                dst := add(dst, 1) // per byte
            } {
                let word := mload(src) // read word (left aligned)
                let b := or(shl(4, getHex(word, 0)), getHex(word, 1)) // "ff" -> 255
                if gt(b, 255) {
                    valid := false
                    break
                }
                mstore8(dst, b) // write ascii byte
            }
        }
    }

    /// @dev Format `address` as a hex string.
    /// @param addr The address to format.
    /// @return hexString The corresponding hex string w/o a 0x-prefix.
    function addressToHex(
        address addr
    ) internal pure returns (string memory hexString) {
        // return bytesToHex(abi.encodePacked(addr));
        hexString = new string(40);
        uint256 dst;
        assembly {
            mstore(0, addr)
            dst := add(hexString, 32)
        }
        unsafeHex(12, dst, 40);
    }

    /// @dev Format `uint256` as a variable-length hex string without zero padding.
    /// * unpaddedUintToHex(0, true)  = "0"
    /// * unpaddedUintToHex(1, true)  = "1"
    /// * unpaddedUintToHex(0, false) = "00"
    /// * unpaddedUintToHex(1, false) = "01"
    /// @param value The number to format.
    /// @param dropZeroNibble If true, the leading byte will use one nibble if less than 16.
    /// @return hexString The corresponding hex string w/o an 0x-prefix.
    function unpaddedUintToHex(
        uint256 value,
        bool dropZeroNibble
    ) internal pure returns (string memory hexString) {
        uint256 temp = value;
        uint256 shift;
        for (uint256 b = 128; b >= 8; b >>= 1) {
            if (temp < (1 << b)) {
                shift += b; // number of zero upper bits
            } else {
                temp >>= b; // shift away lower half
            }
        }
        if (dropZeroNibble && temp < 16) shift += 4;
        uint256 nibbles = 64 - (shift >> 2);
        hexString = new string(nibbles);
        uint256 dst;
        assembly {
            mstore(0, shl(shift, value)) // left-align
            dst := add(hexString, 32)
        }
        unsafeHex(0, dst, nibbles);
    }

    /// @dev Format `bytes` as a hex string.
    /// @param v The bytes to format.
    /// @return hexString The corresponding hex string w/o a 0x-prefix.
    function bytesToHex(
        bytes memory v
    ) internal pure returns (string memory hexString) {
        uint256 nibbles = v.length << 1;
        hexString = new string(nibbles);
        uint256 src;
        uint256 dst;
        assembly {
            src := add(v, 32)
            dst := add(hexString, 32)
        }
        unsafeHex(src, dst, nibbles);
    }

    /// @dev Converts arbitrary memory to a hex string.
    /// @param src The memory offset of first nibble of input.
    /// @param dst The memory offset of first hex-char of output (can alias `src`).
    /// @param nibbles The number of nibbles to convert and the byte-length of the output.
    function unsafeHex(
        uint256 src,
        uint256 dst,
        uint256 nibbles
    ) internal pure {
        unchecked {
            for (uint256 end = dst + nibbles; dst < end; src += 32) {
                uint256 word;
                assembly {
                    word := mload(src)
                }
                for (uint256 shift = 256; dst < end && shift > 0; dst++) {
                    uint256 b = (word >> (shift -= 4)) & 15; // each nibble
                    b = b < 10 ? b + 0x30 : b + 0x57; // ("a" - 10) => 0x57
                    assembly {
                        mstore8(dst, b)
                    }
                }
            }
        }
    }
}

lib/contracts-v2/contracts/lib/ens-contracts/contracts/utils/IERC7996.sol

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

/// @notice Interface for expressing contract features not visible from the ABI.
/// @dev Interface selector: `0x582de3e7`
interface IERC7996 {
    /// @notice Check if a feature is supported.
    /// @param featureId The feature identifier.
    /// @return `true` if the feature is supported by the contract.
    function supportsFeature(bytes4 featureId) external view returns (bool);
}

lib/contracts-v2/contracts/lib/ens-contracts/contracts/utils/LibMem/LibMem.sol

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

library LibMem {
    /// @dev Copy `mem[src:src+len]` to `mem[dst:dst+len]`.
    ///      Equivalent to `mcopy()`.
    ///
    /// @param src The source memory offset.
    /// @param dst The destination memory offset.
    /// @param len The number of bytes to copy.
    function copy(uint256 dst, uint256 src, uint256 len) internal pure {
        assembly {
            // Copy word-length chunks while possible
            // prettier-ignore
            for {} gt(len, 31) {} {
                mstore(dst, mload(src))
                dst := add(dst, 32)
                src := add(src, 32)
                len := sub(len, 32)
            }
            // Copy remaining bytes
            if len {
                let mask := sub(shl(shl(3, sub(32, len)), 1), 1)
                let wSrc := and(mload(src), not(mask))
                let wDst := and(mload(dst), mask)
                mstore(dst, or(wSrc, wDst))
            }
        }
    }

    /// @dev Convert bytes to a memory offset.
    ///
    /// @param v The bytes to convert.
    ///
    /// @return ret The corresponding memory offset.
    function ptr(bytes memory v) internal pure returns (uint256 ret) {
        assembly {
            ret := add(v, 32)
        }
    }

    /// @dev Read word at memory offset.
    ///
    /// @param src The memory offset.
    ///
    /// @return ret The read word.
    function load(uint256 src) internal pure returns (uint256 ret) {
        assembly {
            ret := mload(src)
        }
    }
}

lib/contracts-v2/contracts/lib/ens-contracts/contracts/utils/NameCoder.sol

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

import {LibMem} from "./LibMem/LibMem.sol";
import {BytesUtils} from "./BytesUtils.sol";

/// @dev Library for encoding/decoding names.
///
/// An ENS name is stop-separated labels, eg. "aaa.bb.c".
///
/// A DNS-encoded name is composed of byte length-prefixed labels with a terminator byte.
/// eg. "\x03aaa\x02bb\x01c\x00".
///
/// * maximum label length is 255 bytes.
/// * length = 0 is reserved for the terminator (root).
/// * `dns.length == 2 + ens.length` and the mapping is injective.
///
library NameCoder {
    /// @dev The namehash of "eth".
    bytes32 public constant ETH_NODE =
        0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae;

    /// @dev The label was empty.
    ///      Error selector: `0xbf9a2740`
    error LabelIsEmpty();

    /// @dev The label was more than 255 bytes.
    ///      Error selector: `0xdab6c73c`
    error LabelIsTooLong(string label);

    /// @dev The DNS-encoded name is malformed.
    ///      Error selector: `0xba4adc23`
    error DNSDecodingFailed(bytes dns);

    /// @dev A label of the ENS name has an invalid size.
    ///      Error selector: `0x9a4c3e3b`
    error DNSEncodingFailed(string ens);

    /// @dev The `name` did not end with `suffix`.
    ///
    /// @param name The DNS-encoded name.
    /// @param suffix The DNS-encoded suffix.
    error NoSuffixMatch(bytes name, bytes suffix);

    /// @dev Read the `size` of the label at `offset`.
    ///      If `size = 0`, it must be the end of `name` (no junk at end).
    ///      Reverts `DNSDecodingFailed`.
    ///
    /// @param name The DNS-encoded name.
    /// @param offset The offset into `name` to start reading.
    ///
    /// @return size The size of the label in bytes.
    /// @return nextOffset The offset into `name` of the next label.
    function nextLabel(
        bytes memory name,
        uint256 offset
    ) internal pure returns (uint8 size, uint256 nextOffset) {
        unchecked {
            if (offset >= name.length) {
                revert DNSDecodingFailed(name);
            }
            size = uint8(name[offset]);
            nextOffset = offset + 1 + size;
            if (
                size > 0 ? nextOffset >= name.length : nextOffset != name.length
            ) {
                revert DNSDecodingFailed(name);
            }
        }
    }

    /// @dev Find the offset of the label before `offset` in `name`.
    ///      * `prevOffset(name, 0)` reverts
    ///      * `prevOffset(name, name.length + 1)` reverts
    ///      * `prevOffset(name, name.length) = name.length - 1`
    ///      * `prevOffset(name, name.length - 1) = <tld>`
    ///      Reverts `DNSDecodingFailed`.
    ///
    /// @param name The DNS-encoded name.
    /// @param offset The offset into `name` to start reading backwards.
    ///
    /// @return prevOffset The offset into `name` of the previous label.
    function prevLabel(
        bytes memory name,
        uint256 offset
    ) internal pure returns (uint256 prevOffset) {
        while (true) {
            (, uint256 nextOffset) = nextLabel(name, prevOffset);
            if (nextOffset == offset) break;
            if (nextOffset > offset) {
                revert DNSDecodingFailed(name);
            }
            prevOffset = nextOffset;
        }
    }

    /// @dev Count number of labels in `name`.
    ///      * `countLabels("\x03eth\x00") = 1`
    ///      * `countLabels("\x00") = 0`
    ///      Reverts like `nextLabel()`.
    ///
    /// @param name The DNS-encoded parent name.
    /// @param offset The offset into `name` to start hashing.
    ///
    /// @return count The number of labels.
    function countLabels(
        bytes memory name,
        uint256 offset
    ) internal pure returns (uint256 count) {
        uint8 size;
        while (true) {
            (size, offset) = nextLabel(name, offset);
            if (size == 0) break;
            ++count;
        }
    }

    /// @dev Compute the ENS labelhash of the label at `offset` and the offset for the next label.
    ///      Reverts `DNSDecodingFailed`.
    ///
    /// @param name The DNS-encoded name.
    /// @param offset The offset into `name` to start reading.
    ///
    /// @return labelHash The resulting labelhash.
    /// @return nextOffset The offset into `name` of the next label.
    function readLabel(
        bytes memory name,
        uint256 offset
    ) internal pure returns (bytes32 labelHash, uint256 nextOffset) {
        uint8 size;
        (size, nextOffset) = nextLabel(name, offset);
        if (size > 0) {
            assembly {
                labelHash := keccak256(add(add(name, offset), 33), size)
            }
        }
    }

    /// @dev Read label at offset from a DNS-encoded name and the offset for the next label.
    ///      * `readLabel("\x03abc\x00", 0) = ("abc", 4)`
    ///      * `readLabel("\x00", 0) = ("", 1)`
    ///      Reverts `DNSDecodingFailed`.
    ///
    /// @param name The DNS-encoded name.
    /// @param offset The offset into `name` to start reading.
    ///
    /// @return label The label corresponding to `offset`.
    /// @return nextOffset The offset into `name` of the next label.
    function extractLabel(
        bytes memory name,
        uint256 offset
    ) internal pure returns (string memory label, uint256 nextOffset) {
        uint8 size;
        (size, nextOffset) = nextLabel(name, offset);
        bytes memory v = new bytes(size);
        unchecked {
            LibMem.copy(LibMem.ptr(v), LibMem.ptr(name) + offset + 1, size);
        }
        label = string(v);
    }

    /// @dev Reads first label from a DNS-encoded name.
    ///      Reverts `DNSDecodingFailed`.
    ///      Reverts `LabelIsEmpty` if the label was empty.
    ///
    /// @param name The DNS-encoded name.
    ///
    /// @return The first label.
    function firstLabel(
        bytes memory name
    ) internal pure returns (string memory) {
        (string memory label, ) = extractLabel(name, 0);
        if (bytes(label).length == 0) {
            revert LabelIsEmpty();
        }
        return label;
    }

    /// @dev Compute the namehash of `name[:offset]`.
    ///      Reverts `DNSDecodingFailed`.
    ///
    /// @param name The DNS-encoded name.
    /// @param offset The offset into `name` to start hashing.
    ///
    /// @return hash The namehash of `name[:offset]`.
    function namehash(
        bytes memory name,
        uint256 offset
    ) internal pure returns (bytes32 hash) {
        (hash, offset) = readLabel(name, offset);
        if (hash != bytes32(0)) {
            hash = namehash(namehash(name, offset), hash);
        }
    }

    /// @dev Compute a child namehash from a parent namehash and child labelhash.
    ///
    /// @param parentNode The namehash of the parent.
    /// @param labelHash The labelhash of the child.
    ///
    /// @return node The namehash of the child.
    function namehash(
        bytes32 parentNode,
        bytes32 labelHash
    ) internal pure returns (bytes32 node) {
        // ~100 gas less than: keccak256(abi.encode(parentNode, labelHash))
        assembly {
            mstore(0, parentNode)
            mstore(32, labelHash)
            node := keccak256(0, 64)
        }
    }

    /// @dev Convert DNS-encoded name to ENS name.
    ///      * `decode("\x00") = ""`
    ///      * `decode("\x03eth\x00") = "eth"`
    ///      * `decode("\x03aaa\x02bb\x01c\x00") = "aa.bb.c"`
    ///      * `decode("\x03a.b\x00")` reverts
    ///      Reverts like `nextLabel()`.
    ///
    /// @param dns The DNS-encoded name to convert.
    ///
    /// @return ens The equivalent ENS name.
    function decode(
        bytes memory dns
    ) internal pure returns (string memory ens) {
        unchecked {
            uint256 n = dns.length;
            if (n == 1 && dns[0] == 0) return ""; // only valid answer is root
            if (n < 3) revert DNSDecodingFailed(dns);
            bytes memory v = new bytes(n - 2); // always 2-shorter
            LibMem.copy(LibMem.ptr(v), LibMem.ptr(dns) + 1, n - 2); // shift by -1 byte
            uint256 offset;
            while (true) {
                (uint8 size, uint256 nextOffset) = nextLabel(dns, offset);
                if (size == 0) break;
                if (BytesUtils.includes(v, offset, size, ".")) {
                    revert DNSDecodingFailed(dns); // malicious label
                }
                if (offset > 0) {
                    v[offset - 1] = ".";
                }
                offset = nextOffset;
            }
            return string(v);
        }
    }

    /// @dev Convert ENS name to DNS-encoded name.
    ///      * `encode("aaa.bb.c") = "\x03aaa\x02bb\x01c\x00"`
    ///      * `encode("eth") = "\x03eth\x00"`
    ///      * `encode("") = "\x00"`
    ///      Reverts `DNSEncodingFailed`.
    ///
    /// @param ens The ENS name to convert.
    ///
    /// @return dns The corresponding DNS-encoded name, eg. `\x03aaa\x02bb\x01c\x00`.
    function encode(
        string memory ens
    ) internal pure returns (bytes memory dns) {
        unchecked {
            uint256 n = bytes(ens).length;
            if (n == 0) return hex"00"; // root
            dns = new bytes(n + 2); // always 2-longer
            LibMem.copy(LibMem.ptr(dns) + 1, LibMem.ptr(bytes(ens)), n); // shift by +1 byte
            uint256 start; // remember position to write length
            uint256 size;
            for (uint256 i; i < n; ++i) {
                if (bytes(ens)[i] == ".") {
                    size = i - start;
                    if (size == 0 || size > 255) {
                        revert DNSEncodingFailed(ens);
                    }
                    dns[start] = bytes1(uint8(size));
                    start = i + 1;
                }
            }
            size = n - start;
            if (size == 0 || size > 255) {
                revert DNSEncodingFailed(ens);
            }
            dns[start] = bytes1(uint8(size));
        }
    }

    /// @dev Find the offset into `name` that namehashes to `nodeSuffix`.
    ///
    /// @param name The DNS-encoded name to search.
    /// @param nodeSuffix The namehash to match.
    ///
    /// @return matched True if `name` ends with `nodeSuffix`.
    /// @return node The namehash of `name[offset:]`.
    /// @return prevOffset The offset into `name` of the label before `nodeSuffix`, or `matchOffset` if no match or no prior label.
    /// @return matchOffset The offset into `name` that namehashes to the `nodeSuffix`, or 0 if no match.
    function matchSuffix(
        bytes memory name,
        uint256 offset,
        bytes32 nodeSuffix
    )
        internal
        pure
        returns (
            bool matched,
            bytes32 node,
            uint256 prevOffset,
            uint256 matchOffset
        )
    {
        (bytes32 labelHash, uint256 next) = readLabel(name, offset);
        if (labelHash != bytes32(0)) {
            (matched, node, prevOffset, matchOffset) = matchSuffix(
                name,
                next,
                nodeSuffix
            );
            if (node == nodeSuffix) {
                matched = true;
                prevOffset = offset;
                matchOffset = next;
            }
            node = namehash(node, labelHash);
        }
        if (node == nodeSuffix) {
            matched = true;
            prevOffset = matchOffset = offset;
        }
    }

    /// @dev Assert `label` is an encodable size.
    ///
    /// @param label The label to check.
    ///
    /// @return The size of the label.
    function assertLabelSize(
        string memory label
    ) internal pure returns (uint8) {
        uint256 n = bytes(label).length;
        if (n == 0) revert LabelIsEmpty();
        if (n > 255) revert LabelIsTooLong(label);
        return uint8(n);
    }

    /// @dev Prepend `label` to DNS-encoded `name`.
    ///      * `addLabel("\x03eth\x00", "test") = "\x04test\x03eth\x00"`
    ///      * `addLabel("\x00", "eth") = "\x03eth\x00"`
    ///      * `addLabel("", "abc") = "\x03abc"` invalid
    ///      * `addLabel("", "")` reverts
    ///      Assumes `name` is properly encoded.
    ///      Reverts like `assertLabelSize()`.
    ///
    /// @param name The DNS-encoded parent name.
    /// @param label The child label to prepend.
    ///
    /// @return The DNS-encoded child name.
    function addLabel(
        bytes memory name,
        string memory label
    ) internal pure returns (bytes memory) {
        return abi.encodePacked(assertLabelSize(label), label, name);
    }

    /// @dev Transform `label` to DNS-encoded `{label}.eth`.
    ///      * `ethName("eth") = "\x04test\x03eth\x00"`
    ///      Behaves like `addLabel()`.
    ///
    /// @param label The label to encode.
    ///
    /// @return The DNS-encoded name.
    function ethName(string memory label) internal pure returns (bytes memory) {
        return addLabel("\x03eth\x00", label);
    }
}

lib/contracts-v2/contracts/lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reinitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
     *
     * NOTE: Consider following the ERC-7201 formula to derive storage locations.
     */
    function _initializableStorageSlot() internal pure virtual returns (bytes32) {
        return INITIALIZABLE_STORAGE;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        bytes32 slot = _initializableStorageSlot();
        assembly {
            $.slot := slot
        }
    }
}

lib/contracts-v2/contracts/lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.22;

import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 */
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view virtual notDelegated returns (bytes32) {
        return ERC1967Utils.IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC-1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}

lib/contracts-v2/contracts/lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)

pragma solidity ^0.8.20;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 */
interface IERC1967 {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);
}

lib/contracts-v2/contracts/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC1822.sol)

pragma solidity ^0.8.20;

/**
 * @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

lib/contracts-v2/contracts/lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/ERC1967/ERC1967Utils.sol)

pragma solidity ^0.8.22;

import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";

/**
 * @dev This library provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
 */
library ERC1967Utils {
    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @dev Returns the current implementation address.
     */
    function getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit IERC1967.Upgraded(newImplementation);

        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        if (newAdmin == address(0)) {
            revert ERC1967InvalidAdmin(address(0));
        }
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {IERC1967-AdminChanged} event.
     */
    function changeAdmin(address newAdmin) internal {
        emit IERC1967.AdminChanged(getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the ERC-1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        if (newBeacon.code.length == 0) {
            revert ERC1967InvalidBeacon(newBeacon);
        }

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit IERC1967.BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}

lib/contracts-v2/contracts/lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {UpgradeableBeacon} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

lib/contracts-v2/contracts/lib/openzeppelin-contracts/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @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.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, bytes memory returndata) = recipient.call{value: amount}("");
        if (!success) {
            _revert(returndata);
        }
    }

    /**
     * @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 or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * 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.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @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`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

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

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

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) 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
            assembly ("memory-safe") {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

lib/contracts-v2/contracts/lib/openzeppelin-contracts/contracts/utils/Errors.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

lib/contracts-v2/contracts/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol

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

pragma solidity ^0.8.20;

/**
 * @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 ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 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) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

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

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

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

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            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) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            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) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

lib/contracts-v2/contracts/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 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);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

lib/contracts-v2/contracts/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165Checker.sol

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

pragma solidity ^0.8.20;

import {IERC165} from "./IERC165.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 ERC165Checker {
    // As per the ERC-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 ERC-165 must explicitly indicate support of
        // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
        return
            supportsERC165InterfaceUnchecked(account, type(IERC165).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 ERC-165 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}.
     */
    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 ERC-165 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 ERC-165 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 ERC-165 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 ERC-165, 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.encodeCall(IERC165.supportsInterface, (interfaceId));

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

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

lib/contracts-v2/contracts/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * 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[ERC 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);
}

lib/contracts-v2/contracts/lib/verifiable-factory/src/IProxyAuthorization.sol

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

interface IProxyAuthorization {
    function canUpgradeFrom(address previousImplementation) external view returns (bool);
}

lib/contracts-v2/contracts/src/access-control/EnhancedAccessControl.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (access/AccessControl.sol)

pragma solidity ^0.8.20;

import {ERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";

import {IEnhancedAccessControl} from "./interfaces/IEnhancedAccessControl.sol";
import {EACBaseRolesLib} from "./libraries/EACBaseRolesLib.sol";

/// @dev Resource-scoped access control system with bitmap-packed roles.
///
/// Subclasses define custom roles as constants and assign them to accounts within specific
/// resources. A resource is an arbitrary uint256 identifier whose meaning is determined by
/// the subclass (e.g. a token ID, a name hash, etc.).
///
/// Features:
/// - Resource-based roles: each resource has independent role assignments.
/// - ROOT_RESOURCE fallback: roles granted in `ROOT_RESOURCE` (0x0) automatically apply
///   to all resources. Role checks OR the account's root roles with their resource-specific
///   roles, so holding a role in either scope satisfies the check.
/// - Admin roles: each regular role has a corresponding admin role. Holding an admin role
///   grants authority to grant and revoke both the regular role and the admin role itself.
/// - Assignee counting: per-role assignee counts are tracked, with a maximum of 15 per role.
/// - Callbacks: subclasses can override `_onRolesGranted` and `_onRolesRevoked` to react
///   to role changes (e.g. regenerating tokens, updating metadata).
/// - Separate root operations: `grantRoles`/`revokeRoles` reject `ROOT_RESOURCE` directly;
///   use `grantRootRoles`/`revokeRootRoles` for root-level assignments.
///
/// Bitmap layout (uint256, 64 nybbles):
///
///   255         128 127            0
///   ┌──────────────┬───────────────┐
///   │ Admin Roles  │ Regular Roles │
///   └──────────────┴───────────────┘
///   63           32 31             0
///
/// Each role occupies one nybble (4 bits). A regular role at nybble index N occupies bits
/// N*4 to N*4+3, and its admin counterpart occupies the same relative position in the upper
/// half at bits N*4+128 to N*4+131.
///
/// Defining roles: `uint256 constant MY_ROLE = 1 << (N * 4)` where N is the nybble index
/// (0-31), and the admin role as `uint256 constant MY_ROLE_ADMIN = MY_ROLE << 128`.
///
/// The same nybble-per-role layout is used for assignee counting: each nybble in the count
/// bitmap tracks the number of accounts holding that role within a resource (4 bits = max 15).
///
abstract contract EnhancedAccessControl is ERC165, IEnhancedAccessControl {
    ////////////////////////////////////////////////////////////////////////
    // Constants
    ////////////////////////////////////////////////////////////////////////

    /// @notice The `ROOT_RESOURCE`.
    uint256 public constant ROOT_RESOURCE = 0;

    ////////////////////////////////////////////////////////////////////////
    // Storage
    ////////////////////////////////////////////////////////////////////////

    /// @dev user roles within a resource stored as a bitmap.
    ///      Resource -> User -> RoleBitmap
    mapping(uint256 resource => mapping(address account => uint256 roleBitmap)) private _roles;

    /// @dev The number of assignees for a given role in a given resource.
    ///
    /// Each role's count is represented by 4 bits, in little-endian order.
    /// This results in max. 64 roles, and 15 assignees per role.
    ///
    mapping(uint256 resource => uint256 roleCount) private _roleCount;

    /// @dev Storage gap for future changes.
    uint256[256] private __gap;

    ////////////////////////////////////////////////////////////////////////
    // Modifiers
    ////////////////////////////////////////////////////////////////////////

    /// @dev Modifier that checks that sender has the admin roles for all the given roles.
    modifier canGrantRoles(uint256 resource, uint256 roleBitmap) {
        _checkCanGrantRoles(resource, roleBitmap, msg.sender);
        _;
    }

    /// @dev Modifier that checks that sender has the admin roles for all the given roles and can revoke them.
    modifier canRevokeRoles(uint256 resource, uint256 roleBitmap) {
        _checkCanRevokeRoles(resource, roleBitmap, msg.sender);
        _;
    }

    /// @dev Modifier that checks that sender has all the given roles within the given resource or the ROOT_RESOURCE.
    modifier onlyRoles(uint256 resource, uint256 roleBitmap) {
        _checkRoles(resource, roleBitmap, msg.sender);
        _;
    }

    /// @dev Modifier that checks that sender has all the given roles within the `ROOT_RESOURCE`.
    modifier onlyRootRoles(uint256 roleBitmap) {
        _checkRoles(ROOT_RESOURCE, roleBitmap, msg.sender);
        _;
    }

    ////////////////////////////////////////////////////////////////////////
    // Initialization
    ////////////////////////////////////////////////////////////////////////

    /// @inheritdoc ERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return
            interfaceId == type(IEnhancedAccessControl).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    ////////////////////////////////////////////////////////////////////////
    // Implementation
    ////////////////////////////////////////////////////////////////////////

    /// @inheritdoc IEnhancedAccessControl
    /// @dev The caller must have all the necessary admin roles for the roles being granted.
    ///      Cannot be used with ROOT_RESOURCE directly, use grantRootRoles instead.
    function grantRoles(uint256 resource, uint256 roleBitmap, address account)
        public
        virtual
        canGrantRoles(resource, roleBitmap)
        returns (bool)
    {
        if (resource == ROOT_RESOURCE) {
            revert EACRootResourceNotAllowed();
        }
        return _grantRoles(resource, roleBitmap, account, true);
    }

    /// @inheritdoc IEnhancedAccessControl
    /// @dev The caller must have all the necessary admin roles for the roles being granted.
    function grantRootRoles(uint256 roleBitmap, address account)
        public
        virtual
        canGrantRoles(ROOT_RESOURCE, roleBitmap)
        returns (bool)
    {
        return _grantRoles(ROOT_RESOURCE, roleBitmap, account, true);
    }

    /// @inheritdoc IEnhancedAccessControl
    /// @dev The caller must have all the necessary admin roles for the roles being revoked.
    ///      Cannot be used with ROOT_RESOURCE directly, use revokeRootRoles instead.
    function revokeRoles(uint256 resource, uint256 roleBitmap, address account)
        public
        virtual
        canRevokeRoles(resource, roleBitmap)
        returns (bool)
    {
        if (resource == ROOT_RESOURCE) {
            revert EACRootResourceNotAllowed();
        }
        return _revokeRoles(resource, roleBitmap, account, true);
    }

    /// @inheritdoc IEnhancedAccessControl
    /// @dev The caller must have all the necessary admin roles for the roles being revoked.
    function revokeRootRoles(uint256 roleBitmap, address account)
        public
        virtual
        canRevokeRoles(ROOT_RESOURCE, roleBitmap)
        returns (bool)
    {
        return _revokeRoles(ROOT_RESOURCE, roleBitmap, account, true);
    }

    /// @inheritdoc IEnhancedAccessControl
    function roles(uint256 resource, address account) public view virtual returns (uint256) {
        return _getRoles(resource, account);
    }

    /// @inheritdoc IEnhancedAccessControl
    function roleCount(uint256 resource) public view virtual returns (uint256) {
        return _roleCount[resource];
    }

    /// @inheritdoc IEnhancedAccessControl
    function hasRootRoles(uint256 roleBitmap, address account) public view virtual returns (bool) {
        return _getRoles(ROOT_RESOURCE, account) & roleBitmap == roleBitmap;
    }

    /// @inheritdoc IEnhancedAccessControl
    function hasRoles(uint256 resource, uint256 roleBitmap, address account)
        public
        view
        virtual
        returns (bool)
    {
        return _effectiveRoles(resource, account) & roleBitmap == roleBitmap;
    }

    /// @inheritdoc IEnhancedAccessControl
    function hasAssignees(uint256 resource, uint256 roleBitmap) public view virtual returns (bool) {
        (uint256 counts, ) = getAssigneeCount(resource, roleBitmap);
        return counts != 0;
    }

    /// @inheritdoc IEnhancedAccessControl
    function getAssigneeCount(uint256 resource, uint256 roleBitmap)
        public
        view
        virtual
        returns (uint256 counts, uint256 mask)
    {
        mask = _roleBitmapToMask(roleBitmap);
        counts = _roleCount[resource] & mask;
    }

    ////////////////////////////////////////////////////////////////////////
    // Internal Functions
    ////////////////////////////////////////////////////////////////////////

    /// @dev Transfers all roles from `srcAccount` to `dstAccount` within the same resource.
    ///
    /// This function first revokes all roles from the source account, then grants them to the
    /// destination account. This prevents exceeding max assignees limits during transfer.
    ///
    /// Does nothing if there are no roles to transfer.
    ///
    /// @param resource The resource to transfer roles within.
    /// @param srcAccount The account to transfer roles from.
    /// @param dstAccount The account to transfer roles to.
    /// @param executeCallbacks Whether to execute the callbacks.
    function _transferRoles(
        uint256 resource,
        address srcAccount,
        address dstAccount,
        bool executeCallbacks
    )
        internal
        virtual
    {
        uint256 srcRoles = _roles[resource][srcAccount];
        if (srcRoles != 0) {
            // First revoke roles from source account to free up assignee slots
            _revokeRoles(resource, srcRoles, srcAccount, executeCallbacks);
            // Then grant roles to destination account
            _grantRoles(resource, srcRoles, dstAccount, executeCallbacks);
        }
    }

    /// @dev Grants multiple roles to `account`.
    /// @param resource The resource to grant roles within.
    /// @param roleBitmap The roles bitmap to grant.
    /// @param account The account to grant roles to.
    /// @param executeCallbacks Whether to execute the callbacks.
    /// @return `true` if the roles were granted, `false` otherwise.
    function _grantRoles(
        uint256 resource,
        uint256 roleBitmap,
        address account,
        bool executeCallbacks
    )
        internal
        virtual
        returns (bool)
    {
        if (roleBitmap == 0) {
            return false;
        }
        _checkRoleBitmap(roleBitmap);
        if (account == address(0)) {
            revert EACInvalidAccount();
        }
        uint256 currentRoles = _roles[resource][account];
        uint256 updatedRoles = currentRoles | roleBitmap;

        if (currentRoles != updatedRoles) {
            _roles[resource][account] = updatedRoles;
            uint256 newlyAddedRoles = roleBitmap & ~currentRoles;
            _updateRoleCounts(resource, newlyAddedRoles, true);
            emit EACRolesChanged(resource, account, currentRoles, updatedRoles);
            if (executeCallbacks) {
                _onRolesGranted(resource, account, currentRoles, updatedRoles, roleBitmap);
            }
            return true;
        } else {
            return false;
        }
    }

    /// @dev Attempts to revoke roles from `account` and returns a boolean indicating if roles were revoked.
    /// @param resource The resource to revoke roles within.
    /// @param roleBitmap The roles bitmap to revoke.
    /// @param account The account to revoke roles from.
    /// @param executeCallbacks Whether to execute the callbacks.
    /// @return `true` if the roles were revoked, `false` otherwise.
    function _revokeRoles(
        uint256 resource,
        uint256 roleBitmap,
        address account,
        bool executeCallbacks
    )
        internal
        virtual
        returns (bool)
    {
        _checkRoleBitmap(roleBitmap);
        uint256 currentRoles = _roles[resource][account];
        uint256 updatedRoles = currentRoles & ~roleBitmap;

        if (currentRoles != updatedRoles) {
            _roles[resource][account] = updatedRoles;
            uint256 newlyRemovedRoles = roleBitmap & currentRoles;
            _updateRoleCounts(resource, newlyRemovedRoles, false);
            emit EACRolesChanged(resource, account, currentRoles, updatedRoles);
            if (executeCallbacks) {
                _onRolesRevoked(resource, account, currentRoles, updatedRoles, roleBitmap);
            }
            return true;
        } else {
            return false;
        }
    }

    /// @dev Updates role counts when roles are granted/revoked
    /// @param resource The resource to update counts for
    /// @param roleBitmap The roles being modified
    /// @param isGrant true for grant, false for revoke
    function _updateRoleCounts(uint256 resource, uint256 roleBitmap, bool isGrant) internal {
        uint256 roleMask = _roleBitmapToMask(roleBitmap);

        if (isGrant) {
            // Check for overflow
            if (EACBaseRolesLib.hasZeroNybbles(~(roleMask & _roleCount[resource]))) {
                revert EACMaxAssignees(resource, roleBitmap);
            }
            _roleCount[resource] += roleBitmap;
        } else {
            // Check for underflow
            if (EACBaseRolesLib.hasZeroNybbles(~(roleMask & ~_roleCount[resource]))) {
                revert EACMinAssignees(resource, roleBitmap);
            }
            _roleCount[resource] -= roleBitmap;
        }
    }

    /// @dev Callback for when roles are granted.
    /// @param resource The resource that the roles were granted within.
    /// @param account The account that the roles were granted to.
    /// @param oldRoles The old roles for the account.
    /// @param newRoles The new roles for the account.
    /// @param roleBitmap The roles that were granted.
    function _onRolesGranted(
        uint256 resource,
        address account,
        uint256 oldRoles,
        uint256 newRoles,
        uint256 roleBitmap
    )
        internal
        virtual
    {}

    /// @dev Callback for when roles are revoked.
    /// @param resource The resource that the roles were revoked within.
    /// @param account The account that the roles were revoked from.
    /// @param oldRoles The old roles for the account.
    /// @param newRoles The new roles for the account.
    /// @param roleBitmap The roles that were revoked.
    function _onRolesRevoked(
        uint256 resource,
        address account,
        uint256 oldRoles,
        uint256 newRoles,
        uint256 roleBitmap
    )
        internal
        virtual
    {}

    /// @dev Reverts if `account` does not have all the given roles.
    function _checkRoles(uint256 resource, uint256 roleBitmap, address account)
        internal
        view
        virtual
    {
        if (!hasRoles(resource, roleBitmap, account)) {
            revert EACUnauthorizedAccountRoles(resource, roleBitmap, account);
        }
    }

    /// @dev Reverts if `account` does not have the admin roles for all the given roles.
    function _checkCanGrantRoles(uint256 resource, uint256 roleBitmap, address account)
        internal
        view
        virtual
    {
        uint256 settableRoles = _getSettableRoles(resource, account);
        if ((roleBitmap & ~settableRoles) != 0) {
            revert EACCannotGrantRoles(resource, roleBitmap, account);
        }
    }

    /// @dev Reverts if `account` does not have the admin roles for all the given roles that are being revoked.
    function _checkCanRevokeRoles(uint256 resource, uint256 roleBitmap, address account)
        internal
        view
        virtual
    {
        uint256 revokableRoles = _getRevokableRoles(resource, account);
        if ((roleBitmap & ~revokableRoles) != 0) {
            revert EACCannotRevokeRoles(resource, roleBitmap, account);
        }
    }

    /// @dev Returns the settable roles for `account` within `resource`.
    ///
    /// The settable roles are the roles (both regular and admin) that the account can grant.
    /// An account can grant a regular role if they have the corresponding admin role.
    /// An account can grant an admin role if they have that same admin role.
    ///
    /// @param resource The resource to get settable roles for.
    /// @param account The account to get settable roles for.
    /// @return The settable roles for `account` within `resource`.
    function _getSettableRoles(uint256 resource, address account)
        internal
        view
        virtual
        returns (uint256)
    {
        return EACBaseRolesLib.withAdminRolesApplied(_effectiveRoles(resource, account));
    }

    /// @dev Returns the revokable roles for `account` within `resource`.
    ///
    /// The revokable roles are the roles (including admin roles) that the account can revoke.
    ///
    /// @param resource The resource to get revokable roles for.
    /// @param account The account to get revokable roles for.
    /// @return The revokable roles for `account` within `resource`.
    function _getRevokableRoles(uint256 resource, address account)
        internal
        view
        virtual
        returns (uint256)
    {
        return EACBaseRolesLib.withAdminRolesApplied(_effectiveRoles(resource, account));
    }

    /// @dev Returns the roles bitmap for an account for permission checks.
    function _getRoles(uint256 resource, address account) internal view virtual returns (uint256) {
        return _roles[resource][account];
    }

    ////////////////////////////////////////////////////////////////////////
    // Private Functions
    ////////////////////////////////////////////////////////////////////////

    /// @dev Returns the effective roles bitmap for an account for permission checks.
    function _effectiveRoles(uint256 resource, address account) private view returns (uint256) {
        return _getRoles(ROOT_RESOURCE, account) | _getRoles(resource, account);
    }

    /// @dev Checks if a role bitmap contains only valid role bits.
    /// @param roleBitmap The role bitmap to check.
    function _checkRoleBitmap(uint256 roleBitmap) private pure {
        if ((roleBitmap & ~EACBaseRolesLib.ALL_ROLES) != 0) {
            revert EACInvalidRoleBitmap(roleBitmap);
        }
    }

    /// @dev Converts a role bitmap to a mask.
    ///
    /// The mask is a bitmap where each nybble is set if the corresponding role is in the role bitmap.
    ///
    /// @param roleBitmap The role bitmap to convert.
    /// @return roleMask The mask for the role bitmap.
    function _roleBitmapToMask(uint256 roleBitmap) private pure returns (uint256 roleMask) {
        _checkRoleBitmap(roleBitmap);
        roleMask = roleBitmap | (roleBitmap << 1);
        roleMask |= roleMask << 2;
    }
}

lib/contracts-v2/contracts/src/access-control/interfaces/IEnhancedAccessControl.sol

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

/// @notice Interface for Enhanced Access Control system that allows for:
/// * Resource-based roles
/// * Obtaining assignee count for each role in each resource
/// * Root resource override
/// * Up to 32 roles and 32 corresponding admin roles
/// * Up to 15 assignees per role
///
/// @dev Interface selector: `0x8f452d62`
interface IEnhancedAccessControl {
    ////////////////////////////////////////////////////////////////////////
    // Events
    ////////////////////////////////////////////////////////////////////////

    /// @notice Emitted when roles are changed.
    /// @param resource The resource that the roles were changed within.
    /// @param account The account that the roles were changed for.
    /// @param oldRoleBitmap The old roles for the account.
    /// @param newRoleBitmap The new roles for the account.
    event EACRolesChanged(
        uint256 indexed resource,
        address indexed account,
        uint256 oldRoleBitmap,
        uint256 newRoleBitmap
    );

    ////////////////////////////////////////////////////////////////////////
    // Errors
    ////////////////////////////////////////////////////////////////////////

    /// @dev Error selector: `0x4b27a133`
    error EACUnauthorizedAccountRoles(uint256 resource, uint256 roleBitmap, address account);

    /// @dev Error selector: `0xd1a3b355`
    error EACCannotGrantRoles(uint256 resource, uint256 roleBitmap, address account);

    /// @dev Error selector: `0xa604e318`
    error EACCannotRevokeRoles(uint256 resource, uint256 roleBitmap, address account);

    /// @dev Error selector: `0xc2842458`
    error EACRootResourceNotAllowed();

    /// @dev Error selector: `0xf9165348`
    error EACMaxAssignees(uint256 resource, uint256 role);

    /// @dev Error selector: `0x1f80c19b`
    error EACMinAssignees(uint256 resource, uint256 role);

    /// @dev Error selector: `0x2a7b2d20`
    error EACInvalidRoleBitmap(uint256 roleBitmap);

    /// @dev Error selector: `0xec3fc592`
    error EACInvalidAccount();

    ////////////////////////////////////////////////////////////////////////
    // Functions
    ////////////////////////////////////////////////////////////////////////

    /// @notice Grants all roles in the given role bitmap to `account`.
    /// @param resource The resource to grant roles within.
    /// @param roleBitmap The roles bitmap to grant.
    /// @param account The account to grant roles to.
    /// @return `true` if the roles were granted, `false` otherwise.
    function grantRoles(uint256 resource, uint256 roleBitmap, address account)
        external
        returns (bool);

    /// @notice Grants all roles in the given role bitmap to `account` in the ROOT_RESOURCE.
    /// @param roleBitmap The roles bitmap to grant.
    /// @param account The account to grant roles to.
    /// @return `true` if the roles were granted, `false` otherwise.
    function grantRootRoles(uint256 roleBitmap, address account) external returns (bool);

    /// @notice Revokes all roles in the given role bitmap from `account`.
    /// @param resource The resource to revoke roles within.
    /// @param roleBitmap The roles bitmap to revoke.
    /// @param account The account to revoke roles from.
    /// @return `true` if the roles were revoked, `false` otherwise.
    function revokeRoles(uint256 resource, uint256 roleBitmap, address account)
        external
        returns (bool);

    /// @notice Revokes all roles in the given role bitmap from `account` in the ROOT_RESOURCE.
    /// @param roleBitmap The roles bitmap to revoke.
    /// @param account The account to revoke roles from.
    /// @return `true` if the roles were revoked, `false` otherwise.
    function revokeRootRoles(uint256 roleBitmap, address account) external returns (bool);

    /// @notice Returns the `ROOT_RESOURCE` constant.
    function ROOT_RESOURCE() external view returns (uint256);

    /// @notice Returns the roles bitmap for an account in a resource.
    /// @param resource The resource to get the roles for.
    /// @param account The account to get the roles for.
    /// @return The roles bitmap for the account in the resource.
    function roles(uint256 resource, address account) external view returns (uint256);

    /// @notice Returns the role count bitmap for a resource.
    /// @param resource The resource to get the role count for.
    /// @return count The role count bitmap for the resource.
    function roleCount(uint256 resource) external view returns (uint256);

    /// @notice Checks if the given account has been granted all the given roles in the `ROOT_RESOURCE`.
    /// @param roleBitmap The roles bitmap to check.
    /// @param account The account to check.
    /// @return `true` if `account` has been granted all the given roles in the `ROOT_RESOURCE`, `false` otherwise.
    function hasRootRoles(uint256 roleBitmap, address account) external view returns (bool);

    /// @notice Checks if the given account has been granted all the given roles in the given resource or the `ROOT_RESOURCE`.
    /// @param resource The resource to check.
    /// @param roleBitmap The roles bitmap to check.
    /// @param account The account to check.
    /// @return `true` if `account` has been granted all the given roles in the given resource or the `ROOT_RESOURCE`, `false` otherwise.
    function hasRoles(uint256 resource, uint256 roleBitmap, address account)
        external
        view
        returns (bool);

    /// @notice Checks if any of the roles in the given role bitmap has assignees.
    /// @param resource The resource to check.
    /// @param roleBitmap The roles bitmap to check.
    /// @return `true` if any of the roles in the given role bitmap has assignees, `false` otherwise.
    function hasAssignees(uint256 resource, uint256 roleBitmap) external view returns (bool);

    /// @notice Returns the number of assignees for the roles in the given role bitmap.
    /// @param resource The resource to check.
    /// @param roleBitmap The roles bitmap to check.
    /// @return counts The number of assignees for each of the roles in the given role bitmap, expressed as a packed array of 4-bit ints.
    /// @return mask The mask for the given role bitmap.
    function getAssigneeCount(uint256 resource, uint256 roleBitmap)
        external
        view
        returns (uint256 counts, uint256 mask);
}

lib/contracts-v2/contracts/src/access-control/libraries/EACBaseRolesLib.sol

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

/// @dev Defines the two fundamental bitmasks used by `EnhancedAccessControl`'s nybble-packed role system.
///
/// `ALL_ROLES`: a mask with bit 0 of every nybble set (`0x1111...`), representing one unit in
/// each of the 64 role slots (32 regular + 32 admin). Used for validation (checking no bits
/// outside valid positions are set) and for revoking all roles.
///
/// `ADMIN_ROLES`: same pattern but only in the upper 128 bits (`0x1111...0000...`), masking
/// just the 32 admin role slots. Used to extract which admin roles an account holds.
///
library EACBaseRolesLib {
    ////////////////////////////////////////////////////////////////////////
    // Constants
    ////////////////////////////////////////////////////////////////////////

    /// @dev Mask with bit 0 set in every nybble — represents one unit per role slot across all 64 slots.
    uint256 internal constant ALL_ROLES =
        0x1111111111111111111111111111111111111111111111111111111111111111;

    /// @dev Mask selecting only the 32 admin role nybbles (upper 128 bits).
    uint256 internal constant ADMIN_ROLES =
        0x1111111111111111111111111111111100000000000000000000000000000000;

    ////////////////////////////////////////////////////////////////////////
    // Implementation
    ////////////////////////////////////////////////////////////////////////

    /// @dev Admin roles imply their corresponding regular roles.
    function withAdminRolesApplied(uint256 roleBitmap) internal pure returns (uint256) {
        roleBitmap >>= 128;
        return (roleBitmap << 128) | roleBitmap;
    }

    /// @dev Derive roles bitmap from assignee counts.
    /// @param counts Packed role counts (0-15) as `uint4x64`.
    function fromCounts(uint256 counts) internal pure returns (uint256) {
        return (counts | (counts >> 1) | (counts >> 2) | (counts >> 3)) & ALL_ROLES;
    }

    /// @dev Checks if the given value has any zero nybbles.
    /// @param value The value to check.
    /// @return `true` if the value has any zero nybbles, `false` otherwise.
    function hasZeroNybbles(uint256 value) internal pure returns (bool) {
        // Algorithm source: https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord
        uint256 zeroNybbles;
        unchecked {
            zeroNybbles =
                (value - 0x1111111111111111111111111111111111111111111111111111111111111111) &
                ~value &
                0x8888888888888888888888888888888888888888888888888888888888888888;
        }
        return zeroNybbles != 0;
    }
}

lib/contracts-v2/contracts/src/resolver/interfaces/IPermissionedResolver.sol

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

import {IExtendedResolver} from "@ens/contracts/resolvers/profiles/IExtendedResolver.sol";

import {IEnhancedAccessControl} from "../../access-control/interfaces/IEnhancedAccessControl.sol";

/// @dev Interface selector: `0x91413117`
interface IPermissionedResolver is IExtendedResolver, IEnhancedAccessControl {
    ////////////////////////////////////////////////////////////////////////
    // Events
    ////////////////////////////////////////////////////////////////////////

    /// @notice An alias was changed.
    /// @param indexedFromName The source DNS-encoded name. (indexed bytes, hashed)
    /// @param indexedToName The destination DNS-encoded name. (indexed bytes, hashed)
    /// @param fromName The source DNS-encoded name.
    /// @param toName The destination DNS-encoded name.
    event AliasChanged(
        bytes indexed indexedFromName,
        bytes indexed indexedToName,
        bytes fromName,
        bytes toName
    );

    ////////////////////////////////////////////////////////////////////////
    // Errors
    ////////////////////////////////////////////////////////////////////////

    /// @notice The resolver profile cannot be answered.
    /// @dev Error selector: `0x7b1c461b`
    error UnsupportedResolverProfile(bytes4 selector);

    /// @notice The address could not be converted to `address`.
    /// @dev Error selector: `0x8d666f60`
    error InvalidEVMAddress(bytes addressBytes);

    /// @notice The coin type is not a power of 2.
    /// @dev Error selector: `0x5742bb26`
    error InvalidContentType(uint256 contentType);

    ////////////////////////////////////////////////////////////////////////
    // Functions
    ////////////////////////////////////////////////////////////////////////

    /// @notice Initialize the contract.
    /// @param admin The resolver owner.
    /// @param roleBitmap The roles granted to `admin`.
    /// @param setters The setter calldata that avoids permission checks.
    function initialize(address admin, uint256 roleBitmap, bytes[] calldata setters) external;

    /// @notice Create an alias from `fromName` to `toName`.
    /// @param fromName The source DNS-encoded name.
    /// @param toName The destination DNS-encoded name.
    function setAlias(bytes calldata fromName, bytes calldata toName) external;

    /// @notice Determine which name is queried when `fromName` is resolved.
    /// @param fromName The source DNS-encoded name.
    /// @return toName The destination DNS-encoded name or empty if not aliased.
    function getAlias(bytes memory fromName) external view returns (bytes memory toName);
}

lib/contracts-v2/contracts/src/resolver/libraries/PermissionedResolverLib.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

/// @dev Roles for PermissionedResolver.
library PermissionedResolverLib {
    /// @dev Nybble 0: authorizes setting address records. Root or name.
    uint256 internal constant ROLE_SET_ADDR = 1 << 0;
    /// @dev Nybble 32: authorizes setting ROLE_SET_ADDR.
    uint256 internal constant ROLE_SET_ADDR_ADMIN = ROLE_SET_ADDR << 128;

    /// @dev Nybble 1: authorizes setting text records. Root or name.
    uint256 internal constant ROLE_SET_TEXT = 1 << 4;
    /// @dev Nybble 33: authorizes setting ROLE_SET_TEXT.
    uint256 internal constant ROLE_SET_TEXT_ADMIN = ROLE_SET_TEXT << 128;

    /// @dev Nybble 2: authorizes setting the contenthash record. Root or name.
    uint256 internal constant ROLE_SET_CONTENTHASH = 1 << 8;
    /// @dev Nybble 34: authorizes setting ROLE_SET_CONTENTHASH.
    uint256 internal constant ROLE_SET_CONTENTHASH_ADMIN = ROLE_SET_CONTENTHASH << 128;

    /// @dev Nybble 3: authorizes setting the public key record. Root or name.
    uint256 internal constant ROLE_SET_PUBKEY = 1 << 12;
    /// @dev Nybble 35: authorizes setting ROLE_SET_PUBKEY.
    uint256 internal constant ROLE_SET_PUBKEY_ADMIN = ROLE_SET_PUBKEY << 128;

    /// @dev Nybble 4: authorizes setting ABI records. Root or name.
    uint256 internal constant ROLE_SET_ABI = 1 << 16;
    /// @dev Nybble 36: authorizes setting ROLE_SET_ABI.
    uint256 internal constant ROLE_SET_ABI_ADMIN = ROLE_SET_ABI << 128;

    /// @dev Nybble 5: authorizes setting interface implementer records. Root or name.
    uint256 internal constant ROLE_SET_INTERFACE = 1 << 20;
    /// @dev Nybble 37: authorizes setting ROLE_SET_INTERFACE.
    uint256 internal constant ROLE_SET_INTERFACE_ADMIN = ROLE_SET_INTERFACE << 128;

    /// @dev Nybble 6: authorizes setting the reverse name record. Root or name.
    uint256 internal constant ROLE_SET_NAME = 1 << 24;
    /// @dev Nybble 38: authorizes setting ROLE_SET_NAME.
    uint256 internal constant ROLE_SET_NAME_ADMIN = ROLE_SET_NAME << 128;

    /// @dev Nybble 7: authorizes setting alias targets for name rewriting. Root-only.
    uint256 internal constant ROLE_SET_ALIAS = 1 << 28;
    /// @dev Nybble 39: authorizes setting ROLE_SET_ALIAS.
    uint256 internal constant ROLE_SET_ALIAS_ADMIN = ROLE_SET_ALIAS << 128;

    /// @dev Nybble 8: authorizes clearing (version-bumping) all records for a node. Root or name.
    uint256 internal constant ROLE_CLEAR = 1 << 32;
    /// @dev Nybble 40: authorizes setting ROLE_CLEAR.
    uint256 internal constant ROLE_CLEAR_ADMIN = ROLE_CLEAR << 128;

    /// @dev Nybble 9: authorizes setting data records. Root or name.
    uint256 internal constant ROLE_SET_DATA = 1 << 36;
    /// @dev Nybble 41: authorizes setting ROLE_SET_DATA.
    uint256 internal constant ROLE_SET_DATA_ADMIN = ROLE_SET_DATA << 128;

    /// @dev Nybble 30: authorizes contract naming. Root-only.
    uint256 internal constant ROLE_CAN_NAME = 1 << 120;
    /// @dev Nybble 63: authorizes setting ROLE_CAN_NAME.
    uint256 internal constant ROLE_CAN_NAME_ADMIN = ROLE_CAN_NAME << 128;

    /// @dev Nybble 31: authorizes UUPS proxy upgrades. Root-only.
    uint256 internal constant ROLE_UPGRADE = 1 << 124;
    /// @dev Nybble 63: authorizes setting ROLE_UPGRADE.
    uint256 internal constant ROLE_UPGRADE_ADMIN = ROLE_UPGRADE << 128;

    /// @dev Computes `keccak256(node, part)` to create a unique EAC resource ID scoped to both
    ///      a name and a record type. Enables fine-grained per-record permissions.
    /// @param node The ENS namehash of the name.
    /// @param part The record-type identifier (e.g. from `addrPart` or `textPart`).
    /// @return ret The computed resource ID.
    function resource(bytes32 node, bytes32 part) internal pure returns (uint256 ret) {
        if (node != bytes32(0) || part != bytes32(0)) {
            assembly {
                mstore(0, node)
                mstore(32, part)
                ret := keccak256(0, 64)
            }
            // Equivalent: return uint256(keccak256(abi.encode(node, part)));
        }
    }

    /// @dev Computes a record-type identifier for uint256-keyed records.
    /// @param x The uint256 value.
    /// @return part The computed record-type identifier.
    function partHash(uint256 x) internal pure returns (bytes32 part) {
        assembly {
            mstore(0, x)
            part := keccak256(0, 32)
        }
    }

    /// @dev Computes a record-type identifier for string-keyed records.
    /// @param x The string value.
    /// @return part The computed record-type identifier.
    function partHash(string memory x) internal pure returns (bytes32) {
        return keccak256(bytes(x));
    }
}

lib/contracts-v2/contracts/src/resolver/libraries/ResolverProfileRewriterLib.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

/// @dev Rewrites the `bytes32 node` parameter in resolver calldata. Resolver functions follow
/// the convention `func(bytes32 node, ...)`, with the node at calldata offset 4. This library
/// replaces that node in a memory copy of the calldata, recursively handling `multicall(bytes[])`
/// (selector `0xac9650d8`) to rewrite the node in every nested call at arbitrary depth.
///
/// Used by `PermissionedResolver` when resolving aliased names: after determining the alias target,
/// the original calldata must be updated with the new node before forwarding to the actual
/// resolver logic.
///
library ResolverProfileRewriterLib {
    /// @dev Replace the node in the calldata with a new node.
    ///      Supports `multicall()` to arbitrary depth.
    /// @param call The calldata for a resolver.
    /// @param newNode The replacement node.
    /// @return copy A copy of the calldata with node replaced.
    function replaceNode(bytes calldata call, bytes32 newNode)
        internal
        pure
        returns (bytes memory copy)
    {
        // 0xac9650d8                                                       // selector
        // 0000000000000000000000000000000000000000000000000000000000000020 // jump
        // 0000000000000000000000000000000000000000000000000000000000000002 // .length @ jump
        // 0000000000000000000000000000000000000000000000000000000000000040 // jump[0]
        // 00000000000000000000000000000000000000000000000000000000000000a0 // jump[1]
        // 0000000000000000000000000000000000000000000000000000000000000024 // [0].length @ jump[0]
        // ...
        // 0000000000000000000000000000000000000000000000000000000000000024 // [1].length @ jump[1]
        // ...
        copy = call; // make a copy
        assembly {
            function replace(ptr, bound, node) {
                ptr := add(ptr, 36) // skip length + selector
                switch shr(224, mload(sub(ptr, 4))) // read selector
                case 0xac9650d8 {
                    // multicall(bytes[])
                    let lower := ptr
                    ptr := add(ptr, mload(ptr)) // follow jump
                    if lt(ptr, lower) {
                        leave // underflow
                    }
                    let size := shl(5, mload(ptr)) // read word count as size
                    // prettier-ignore
                    for { } size { size := sub(size, 32) } { // backwards
                        lower := add(ptr, 32)
                        let p := add(lower, mload(add(ptr, size))) // local ptr
                        if lt(p, lower) {
                            continue // underflow
                        }
                        let b := add(p, mload(p)) // local bound w/room for 1 word
                        if lt(bound, b) {
                            b := bound // global bound is smaller
                        }
                        replace(p, b, node)
                    }
                }
                default {
                    // only bound checks on write
                    if lt(bound, ptr) {
                        leave
                    }
                    mstore(ptr, node) // replace node
                }
            }
            replace(copy, add(copy, mload(copy)), newNode) // bound w/room for 1 word
        }
    }
}

lib/contracts-v2/contracts/src/reverse-registrar/interfaces/IContractNamer.sol

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

/// @dev Interface selector: `0x6f3ff726`
interface IContractNamer {
    /// @notice Determine if an account is authorized to name this contract.
    ///         Called by reverse registrars.
    /// @param namer The address to check.
    /// @return `true` if authorized.
    function isContractNamer(address namer) external view returns (bool);
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 1000,
    "enabled": true
  },
  "evmVersion": "shanghai",
  "remappings": [
    "forge-std/=lib/contracts-v2/contracts/lib/forge-std/src/",
    "@ensv2/=lib/contracts-v2/contracts/src/",
    "@openzeppelin/contracts/=lib/contracts-v2/contracts/lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-v5/=lib/contracts-v2/contracts/lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/contracts-v2/contracts/lib/openzeppelin-contracts-upgradeable/contracts/",
    "@ens/contracts/=lib/contracts-v2/contracts/lib/ens-contracts/contracts/",
    "@ensdomains/buffer/=lib/contracts-v2/contracts/lib/buffer/",
    "@ensdomains/verifiable-factory/=lib/contracts-v2/contracts/lib/verifiable-factory/src/",
    "@unruggable/gateways/=lib/contracts-v2/contracts/lib/unruggable-gateways/",
    "solady/=lib/contracts-v2/contracts/lib/solady/src/",
    "lib/contracts-v2/contracts/lib/ens-contracts/:@openzeppelin/contracts/=lib/contracts-v2/contracts/lib/openzeppelin-contracts-v4/contracts/",
    "lib/contracts-v2/contracts/lib/ens-contracts/:@openzeppelin/contracts-v5/=lib/contracts-v2/contracts/lib/openzeppelin-contracts/contracts/",
    "lib/contracts-v2/contracts/lib/ens-contracts/:@ensdomains/solsha1/contracts/=lib/contracts-v2/contracts/lib/solsha1/contracts/",
    "lib/contracts-v2/contracts/lib/ens-contracts/:@unruggable/gateways/=lib/contracts-v2/contracts/lib/unruggable-gateways/contracts/",
    "buffer/=lib/contracts-v2/contracts/lib/buffer/contracts/",
    "contracts-v2/=lib/contracts-v2/",
    "ens-contracts/=lib/contracts-v2/contracts/lib/ens-contracts/contracts/",
    "openzeppelin-contracts-upgradeable/=lib/contracts-v2/contracts/lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts-v4/=lib/contracts-v2/contracts/lib/openzeppelin-contracts-v4/",
    "openzeppelin-contracts/=lib/contracts-v2/contracts/lib/openzeppelin-contracts/",
    "optimism/=lib/contracts-v2/contracts/lib/unruggable-gateways/lib/optimism/packages/contracts-bedrock/src/",
    "solsha1/=lib/contracts-v2/contracts/lib/solsha1/contracts/",
    "unruggable-gateways/=lib/contracts-v2/contracts/lib/unruggable-gateways/contracts/",
    "verifiable-factory/=lib/contracts-v2/contracts/lib/verifiable-factory/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.