Skip to content
Verified contractExactMIT

IDLinkedResolver

Address0x104f0c0d2763334430c44585a7f97acde67ad2d1
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
prague
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
24,694,573
Creation transaction
0x1efac84401…991373829a

src/resolvers/IDLinkedResolver.sol

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

import {ERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import {IDRegistry} from "../IDRegistry.sol";
import {NameCoder} from "../utils/NameCoder.sol";
import {IENS, INameWrapper} from "./IENS.sol";

/**
 * @title IDLinkedResolver
 * @notice ENSIP-10 resolver that reads directly from IDRegistry and supports
 *         linking .eth names to agent IDs on the same chain.
 * @dev For linked names, verifies a back-link text record on-chain:
 *      registry.text(agentNode, "ens-link[alice.eth]") == "true"
 */
contract IDLinkedResolver is ERC165 {

    // Function selectors for ENS resolution
    bytes4 private constant ADDR_SELECTOR = 0x3b3b57de; // addr(bytes32)
    bytes4 private constant ADDR_COINTYPE_SELECTOR = 0xf1cb7e06; // addr(bytes32,uint256)
    bytes4 private constant TEXT_SELECTOR = 0x59d1d43c; // text(bytes32,string)
    bytes4 private constant CONTENTHASH_SELECTOR = 0xbc1c58d1; // contenthash(bytes32)
    bytes4 private constant DATA_SELECTOR = 0xecbfada3; // data(bytes32,string) ENSIP-24
    bytes4 private constant RESOLVE_SELECTOR = 0x9061b923; // resolve(bytes,bytes)

    // Back-link verification constant
    bytes32 private constant TRUE_HASH = keccak256("true");

    // DNS suffix for xid.eth: \x03xid\x03eth\x00 — xid.eth names skip linking
    bytes32 private constant XID_ETH_SUFFIX_HASH = keccak256(hex"037869640365746800");

    // Events
    event LinkSet(bytes32 indexed ensNode, bytes32 indexed agentNode, address indexed sender);
    event LinkRemoved(bytes32 indexed ensNode, address indexed sender);

    // Custom errors
    error NotAuthorised();
    error BackLinkNotSet();

    // State
    IDRegistry public immutable idRegistry;
    IENS public immutable ensRegistry;
    address public immutable nameWrapper;
    mapping(bytes32 => bytes32) public links; // ensNode => agentNode

    constructor(IDRegistry _idRegistry, address _ensRegistry, address _nameWrapper) {
        idRegistry = _idRegistry;
        ensRegistry = IENS(_ensRegistry);
        nameWrapper = _nameWrapper;
    }

    /**
     * @dev ENSIP-10 resolve entry point.
     *      Walks up the DNS name labels looking for a forward link at any level.
     *      If found, verifies the back-link on-chain and resolves the linked agent's records.
     *      For subname queries (e.g. treo.alice.eth where alice.eth is linked),
     *      prepends the prefix labels onto the agentNode to compute the target.
     *      xid.eth names always resolve directly, never via links.
     */
    function resolve(bytes calldata name, bytes calldata data) external view returns (bytes memory) {
        bytes32 resolveNode;

        if (!_isXidEthName(name)) {
            // Walk up DNS labels looking for a link at any level
            uint256 offset = 0;
            while (offset < name.length) {
                uint256 labelLen = uint256(uint8(name[offset]));
                if (labelLen == 0) break;

                bytes32 node = NameCoder.namehash(name, offset);
                bytes32 agentNode = links[node];

                if (agentNode != bytes32(0)) {
                    // Found link — verify back-link using the linked parent's ENS name
                    string memory parentName = NameCoder.decode(name[offset:]);
                    string memory key = string.concat("ens-link[", parentName, "]");
                    string memory value = idRegistry.text(agentNode, key);
                    if (keccak256(bytes(value)) != TRUE_HASH) revert BackLinkNotSet();

                    // Prepend prefix labels onto agentNode to get target
                    resolveNode = _prependLabels(name, 0, offset, agentNode);
                    break;
                }

                offset += 1 + labelLen;
            }

            // No link found — resolve directly from IDRegistry
            if (resolveNode == bytes32(0)) {
                resolveNode = NameCoder.namehash(name, 0);
            }
        } else {
            // xid.eth name — always resolve directly
            resolveNode = NameCoder.namehash(name, 0);
        }

        bytes4 selector = bytes4(data);

        if (selector == ADDR_SELECTOR) {
            address payable addr = idRegistry.addr(resolveNode);
            return abi.encode(addr);
        } else if (selector == ADDR_COINTYPE_SELECTOR) {
            (, uint256 coinType) = abi.decode(data[4:], (bytes32, uint256));
            bytes memory addrBytes = idRegistry.addr(resolveNode, coinType);
            return abi.encode(addrBytes);
        } else if (selector == TEXT_SELECTOR) {
            (, string memory key) = abi.decode(data[4:], (bytes32, string));
            string memory value = idRegistry.text(resolveNode, key);
            return abi.encode(value);
        } else if (selector == CONTENTHASH_SELECTOR) {
            bytes memory hash = idRegistry.contenthash(resolveNode);
            return abi.encode(hash);
        } else if (selector == DATA_SELECTOR) {
            (, string memory key) = abi.decode(data[4:], (bytes32, string));
            bytes memory value = idRegistry.data(resolveNode, key);
            return abi.encode(value);
        }

        revert("Unsupported function");
    }

    // --- Link management ---

    function setLink(bytes32 ensNode, bytes32 agentNode) external {
        if (!_isAuthorised(ensNode)) revert NotAuthorised();
        links[ensNode] = agentNode;
        emit LinkSet(ensNode, agentNode, msg.sender);
    }

    function removeLink(bytes32 ensNode) external {
        if (!_isAuthorised(ensNode)) revert NotAuthorised();
        delete links[ensNode];
        emit LinkRemoved(ensNode, msg.sender);
    }

    // --- Internal ---

    /// @dev Returns true if msg.sender is the ENS name owner (unwrapped or wrapped).
    function _isAuthorised(bytes32 node) internal view returns (bool) {
        address owner = ensRegistry.owner(node);
        if (owner == nameWrapper) {
            return msg.sender == INameWrapper(nameWrapper).ownerOf(uint256(node));
        }
        return msg.sender == owner;
    }

    /// @dev Prepend DNS labels from name[start:end] onto baseNode.
    ///      Recursively hashes labels from innermost to outermost.
    ///      Used to compute e.g. namehash("treo.agent-1.base.xid.eth")
    ///      from agentNode=namehash("agent-1.base.xid.eth") and prefix "treo".
    function _prependLabels(bytes calldata name, uint256 start, uint256 end, bytes32 baseNode) internal pure returns (bytes32) {
        if (start >= end) return baseNode;
        uint256 labelLen = uint256(uint8(name[start]));
        bytes32 labelHash = keccak256(name[start + 1 : start + 1 + labelLen]);
        bytes32 inner = _prependLabels(name, start + 1 + labelLen, end, baseNode);
        return keccak256(abi.encodePacked(inner, labelHash));
    }

    /// @dev Returns true if the DNS-encoded name ends with .xid.eth suffix.
    ///      xid.eth names always resolve directly from IDRegistry, never via links.
    function _isXidEthName(bytes calldata name) internal pure returns (bool) {
        return name.length >= 9
            && keccak256(name[name.length - 9:]) == XID_ETH_SUFFIX_HASH;
    }

    // --- ERC-165 ---

    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == RESOLVE_SELECTOR || // ENSIP-10
               interfaceId == DATA_SELECTOR ||    // ENSIP-24
               super.supportsInterface(interfaceId);
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (access/AccessControl.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;


    /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
    struct AccessControlStorage {
        mapping(bytes32 role => RoleData) _roles;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;

    function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
        assembly {
            $.slot := AccessControlStorageLocation
        }
    }

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    function __AccessControl_init() internal onlyInitializing {
    }

    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    /// @inheritdoc ERC165Upgradeable
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        return $._roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        return $._roles[role].adminRole;
    }

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

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

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

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        AccessControlStorage storage $ = _getAccessControlStorage();
        bytes32 previousAdminRole = getRoleAdmin(role);
        $._roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        if (!hasRole(role, account)) {
            $._roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        if (hasRole(role, account)) {
            $._roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol

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

pragma solidity ^0.8.20;
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";

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

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

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

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol

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

pragma solidity ^0.8.20;

import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165 {
    function __ERC165_init() internal onlyInitializing {
    }

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

lib/openzeppelin-contracts/contracts/access/IAccessControl.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (access/IAccessControl.sol)

pragma solidity ^0.8.20;

/**
 * @dev External interface of AccessControl declared to support ERC-165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted to signal this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

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

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

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

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

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

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

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/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/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/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/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol

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

pragma solidity ^0.8.22;

import {IERC1822Proxiable} from "../../interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "../ERC1967/ERC1967Utils.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 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();
        _;
    }

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

src/IDRegistry.sol

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

/**
 * @title IDRegistry
 * @notice An ENS registry with hierarchical namespace management
 * 
 * @dev This contract provides a comprehensive system for managing IDs (ENS subdomains)
 * with the following key features:
 * 
 * - Hierarchical namespace structure (parent/subdomain relationships)
 * - Rich profile data (text records, address records, contenthash)
 * - Subdomain emancipation through time-locked controls
 * - Transfer mode protection against front-running attacks
 * - Subdomain time-lock controller system for secure subdomain management
 * - Registrar controllers with limited permissions for specific nodes
 * 
 * The contract uses a dual-protection mechanism:
 * 1. Lock system: Parents can "emancipate" subdomains with time locks
 * 2. Transfer mode: Automatic cooldowns prevent malicious last-minute changes
 * 
 * @author @nxt3d
 */

import {ERC165Upgradeable} from "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";


contract IDRegistry is Initializable, UUPSUpgradeable, ERC165Upgradeable, AccessControlUpgradeable {

    // Roles
    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");

    // Custom Errors
    error NotAuthorised(bytes32 node, address caller);
    error NotRegistrar(bytes32 node, address caller);
    error NodeDoesNotExist(bytes32 node);
    error KeysArrayLengthMismatch(uint256 keysLength, uint256 valuesLength);
    error CoinTypesArrayLengthMismatch(uint256 coinTypesLength, uint256 addressesLength);
    error NodeLocked(bytes32 node, uint256 lockExpiration);
    error NotLockController(bytes32 node, address caller);
    error CannotReduceLockTime(uint256 currentExpiration, uint256 newExpiration);
    error NotInTransferMode(bytes32 node);
    error TransferModeLockTimeTooLong(uint256 requestedTime, uint256 maxTime);

    // Events
    event NewSubnodeOwner(bytes32 indexed node, bytes32 indexed label, address owner, string labelString);
    event TransferNode(bytes32 indexed node, address owner);
    
    // Profile Events
    event TextChanged(bytes32 indexed node, string key, string value);
    event AddressChanged(bytes32 indexed node, uint256 coinType, bytes newAddress);
    event ContenthashChanged(bytes32 indexed node, bytes hash);
    event DataChanged(bytes32 indexed node, string key, bytes value);
    
    // Lock Events
    event NodeLockSet(bytes32 indexed node, uint256 lockExpiration);
    event LockExtended(bytes32 indexed node, uint256 newExpiration);
    event LockControllerAdded(bytes32 indexed node, address indexed controller);
    event LockControllerRemoved(bytes32 indexed node, address indexed controller);
    
    // Approval Events
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    // Registrar Events
    event RegistrarAdded(bytes32 indexed node, address indexed registrar);
    event RegistrarRemoved(bytes32 indexed node, address indexed registrar);
    
    // Transfer Mode Events
    event TransferModeDisabled(bytes32 indexed node, uint256 disabledUntil);
    event TransferModeLockTimeUpdated(uint256 newLockTime);

    // Approvals from owners to approved addresses
    mapping(address owner => mapping(address approved => bool)) public approvals;
    
    // Registrar system for limited permissions on specific nodes
    mapping(bytes32 node => mapping(address registrar => bool)) public registrars;
    
    // Lock system for subdomain emancipation
    mapping(bytes32 node => uint256 lockExpiration) public lockExpirations;
    mapping(bytes32 node => mapping(address controller => bool)) public lockExpirationControllers;
    
    // Transfer mode system to prevent front-running attacks during sales
    // Transfer mode is DEFAULT (true). When disabled, it auto-re-enables after cooldown
    mapping(bytes32 node => uint256 transferModeDisabledUntil) public transferModeDisabledUntil;
    uint256 public transferModeLockTime; // To start, 0 = no cooldown
    uint256 public constant MAX_TRANSFER_MODE_LOCK_TIME = 1 days; // Maximum 1 day cooldown
    
    struct Record {
        address owner;
        string label; // Store the original human-readable label
        mapping(string key => string value) textRecords;
        mapping(uint256 coinType => bytes addr) addressRecords;
        bytes contenthash;
        mapping(string key => bytes value) dataRecords; // ENSIP-24
    }

    mapping(bytes32 node => Record record) records;

    modifier authorized(bytes32 node) {
        address nodeOwner = records[node].owner;
        require(
            nodeOwner == msg.sender || approvals[nodeOwner][msg.sender],
            NotAuthorised(node, msg.sender)
        );
        _;
    }

    modifier authorizedOrRegistrar(bytes32 node) {
        address nodeOwner = records[node].owner;
        require(
            nodeOwner == msg.sender || approvals[nodeOwner][msg.sender] || registrars[node][msg.sender],
            NotAuthorised(node, msg.sender)
        );
        _;
    }

    modifier onlyRegistrar(bytes32 node) {
        require(
            registrars[node][msg.sender],
            NotRegistrar(node, msg.sender)
        );
        _;
    }

    modifier onlyLockController(bytes32 node) {
        require(
            lockExpirationControllers[node][msg.sender],
            NotLockController(node, msg.sender)
        );
        _;
    }

    constructor() {
        _disableInitializers();
    }

    function initialize(address _admin) public initializer {
        __ERC165_init();
        __AccessControl_init();

        // Root node is owned by the admin
        records[0x0].owner = _admin;

        // Set up roles
        _grantRole(DEFAULT_ADMIN_ROLE, _admin);
        _grantRole(ADMIN_ROLE, _admin);
    }

    // Registry Functions

    /**
     * @dev Sets the owner of a node
     * Can only be called when the node is in transfer mode (secure state)
     */
    function setOwner(bytes32 node, address newOwner) external authorized(node) {
        // Ensure the node is in transfer mode (secure state for ownership changes)
        require(
            block.timestamp >= transferModeDisabledUntil[node],
            NotInTransferMode(node)
        );

        // NOTE: Do we want names that are not locked to be able to change owner?
        
        records[node].owner = newOwner;
        emit TransferNode(node, newOwner);
    }

    /**
     * @dev Sets up a new subdomain
     * @param node The parent node (caller must own this or be a registrar)
     * @param label The human-readable label for the subdomain (e.g., "alice", "subdomain")
     * @param newOwner The owner for the new subdomain
     */
    function setSubnodeOwner(
        bytes32 node,
        string memory label,
        address newOwner
    ) external authorizedOrRegistrar(node) returns (bytes32) {
        bytes32 labelhash = keccak256(bytes(label));
        bytes32 subnode = keccak256(abi.encodePacked(node, labelhash));
        
        // Check if subnode is locked (prevents parent from changing subdomain owner)
        require(
            block.timestamp > lockExpirations[subnode],
            NodeLocked(subnode, lockExpirations[subnode])
        );

        // Ensure the subnode is in transfer mode (secure state for ownership changes)
        require(
            block.timestamp >= transferModeDisabledUntil[subnode],
            NotInTransferMode(subnode)
        );
        
        records[subnode].owner = newOwner;
        
        // Only set label if it hasn't been set yet (label is immutable once set)
        if (bytes(records[subnode].label).length == 0) {
            records[subnode].label = label;
        }
        
        emit TransferNode(subnode, newOwner);
        emit NewSubnodeOwner(node, labelhash, newOwner, label);
        return subnode;
    }

    /**
     * @dev Sets a complete record for a subnode using parent + label pattern
     * @param parentNode The parent node (caller must own this or be a registrar)
     * @param label The human-readable label for the subdomain (e.g., "alice", "subdomain")
     * @param newOwner The new owner for the subnode
     * @param keys Array of text record keys
     * @param values Array of text record values
     * @param coinTypes Array of coin types for address records
     * @param addresses Array of address records
     * @param contentHash Content hash
     */
    function setSubnodeRecord(
        bytes32 parentNode,
        string memory label,
        address newOwner,
        string[] memory keys,
        string[] memory values,
        uint256[] memory coinTypes,
        bytes[] memory addresses,
        bytes memory contentHash,
        string[] memory dataKeys,
        bytes[] memory dataValues
    ) external authorizedOrRegistrar(parentNode) returns (bytes32) {
        bytes32 labelhash = keccak256(bytes(label));
        bytes32 subnode = keccak256(abi.encodePacked(parentNode, labelhash));

        // Validate array lengths
        require(keys.length == values.length, KeysArrayLengthMismatch(keys.length, values.length));
        require(coinTypes.length == addresses.length, CoinTypesArrayLengthMismatch(coinTypes.length, addresses.length));
        require(dataKeys.length == dataValues.length, KeysArrayLengthMismatch(dataKeys.length, dataValues.length));

        // Check if subnode is locked (prevents parent from changing subdomain)
        require(
            block.timestamp > lockExpirations[subnode],
            NodeLocked(subnode, lockExpirations[subnode])
        );

        // Allow changes if in transfer mode or owner remains the same
        require(
            block.timestamp >= transferModeDisabledUntil[subnode] ||
            newOwner == records[subnode].owner,
            NotInTransferMode(subnode)
        );

        // Set owner if it's changing
        if (records[subnode].owner != newOwner) {
            records[subnode].owner = newOwner;
            emit TransferNode(subnode, newOwner);
            emit NewSubnodeOwner(parentNode, labelhash, newOwner, label);
        }

        // Only set label if it hasn't been set yet (label is immutable once set)
        if (bytes(records[subnode].label).length == 0) {
            records[subnode].label = label;
        }

        // Set text records
        for (uint i = 0; i < keys.length; i++) {
            records[subnode].textRecords[keys[i]] = values[i];
            emit TextChanged(subnode, keys[i], values[i]);
        }

        // Set address records
        for (uint i = 0; i < coinTypes.length; i++) {
            records[subnode].addressRecords[coinTypes[i]] = addresses[i];
            emit AddressChanged(subnode, coinTypes[i], addresses[i]);
        }

        // Only set the contenthash if it's changing and not empty
        if (keccak256(records[subnode].contenthash) != keccak256(contentHash) && contentHash.length > 0) {
            records[subnode].contenthash = contentHash;
            emit ContenthashChanged(subnode, contentHash);
        }

        // Set data records (ENSIP-24)
        for (uint i = 0; i < dataKeys.length; i++) {
            records[subnode].dataRecords[dataKeys[i]] = dataValues[i];
            emit DataChanged(subnode, dataKeys[i], dataValues[i]);
        }

        return subnode;
    }

    /**
     * @dev Sets records for a specific node (does not change ownership)
     */
    function setRecord(
        bytes32 node,
        string[] memory keys,
        string[] memory values,
        uint256[] memory coinTypes,
        bytes[] memory addresses,
        bytes memory contentHash,
        string[] memory dataKeys,
        bytes[] memory dataValues
    ) external authorized(node) {
        // Validate array lengths
        require(keys.length == values.length, KeysArrayLengthMismatch(keys.length, values.length));
        require(coinTypes.length == addresses.length, CoinTypesArrayLengthMismatch(coinTypes.length, addresses.length));
        require(dataKeys.length == dataValues.length, KeysArrayLengthMismatch(dataKeys.length, dataValues.length));

        // Set text records
        for (uint i = 0; i < keys.length; i++) {
            records[node].textRecords[keys[i]] = values[i];
            emit TextChanged(node, keys[i], values[i]);
        }

        // Set address records
        for (uint i = 0; i < coinTypes.length; i++) {
            records[node].addressRecords[coinTypes[i]] = addresses[i];
            emit AddressChanged(node, coinTypes[i], addresses[i]);
        }

        // Set contenthash (allows clearing with empty bytes, unlike setContenthash)
        if (keccak256(records[node].contenthash) != keccak256(contentHash)) {
            records[node].contenthash = contentHash;
            emit ContenthashChanged(node, contentHash);
        }

        // Set data records (ENSIP-24)
        for (uint i = 0; i < dataKeys.length; i++) {
            records[node].dataRecords[dataKeys[i]] = dataValues[i];
            emit DataChanged(node, dataKeys[i], dataValues[i]);
        }
    }

    /**
     * @dev Transfers ownership of a node to a new address
     * Can only be called by the current owner when the node is in transfer mode
     */
    function transferNode(
        bytes32 node,
        address newOwner
    ) external authorized(node) {
        require(newOwner != address(0), "Cannot transfer to zero address");
        require(
            block.timestamp >= transferModeDisabledUntil[node],
            NotInTransferMode(node)
        );

        records[node].owner = newOwner;
        emit TransferNode(node, newOwner);
    }

    /**
     * @dev Burns a node by setting its owner to address(0)
     * Can only be called by the current owner when the node is in transfer mode
     */
    function burnNode(bytes32 node) external authorized(node) {
        require(
            block.timestamp >= transferModeDisabledUntil[node],
            NotInTransferMode(node)
        );

        records[node].owner = address(0);
        emit TransferNode(node, address(0));
    }

    /**
     * @dev Sets a text record for a specific node
     */
    function setText(
        bytes32 node,
        string memory key,
        string memory value
    ) external authorized(node) {
        
        records[node].textRecords[key] = value;
        emit TextChanged(node, key, value);
    }

    /**
     * @dev Sets an address record for a specific node
     */
    function setAddr(
        bytes32 node,
        uint256 coinType,
        bytes memory address_
    ) external authorized(node) {
        
        records[node].addressRecords[coinType] = address_;
        emit AddressChanged(node, coinType, address_);
    }

    /**
     * @dev Sets ETH address for a node (convenience function)
     */
    function setAddr(bytes32 node, address address_) external authorized(node) {
        
        records[node].addressRecords[60] = abi.encodePacked(address_);
        emit AddressChanged(node, 60, abi.encodePacked(address_));
    }

    /**
     * @dev Sets content hash for a specific node
     */
    function setContenthash(
        bytes32 node,
        bytes memory contentHash
    ) external authorized(node) {

        records[node].contenthash = contentHash;
        emit ContenthashChanged(node, contentHash);
    }

    /**
     * @dev Sets an ENSIP-24 data record for a specific node
     */
    function setData(
        bytes32 node,
        string memory key,
        bytes memory value
    ) external authorized(node) {
        records[node].dataRecords[key] = value;
        emit DataChanged(node, key, value);
    }

    /**
     * @dev Sets approval for an operator to manage all caller's nodes
     * @param operator The address to approve or revoke approval for
     * @param approved Whether to approve or revoke approval
     */
    function setApprovalForAll(address operator, bool approved) external {
        // Users can only set approvals for themselves
        approvals[msg.sender][operator] = approved;
        emit ApprovalForAll(msg.sender, operator, approved);
    }

    /**
     * @dev Checks if operator is approved for owner
     */
    function isApprovedForAll(address nodeOwner, address operator) external view returns (bool) {
        return approvals[nodeOwner][operator];
    }

    // View Functions

    /**
     * @dev Gets the owner of a node
     */
    function owner(bytes32 node) external view returns (address) {
        address nodeOwner = records[node].owner;
        return nodeOwner;
    }

    /**
     * @dev Gets a text record
     */
    function text(bytes32 node, string memory key) external view returns (string memory) {
        return records[node].textRecords[key];
    }

    /**
     * @dev Gets an address record (with override priority)
     */
    function addr(bytes32 node, uint256 coinType) external view returns (bytes memory) {
        return records[node].addressRecords[coinType];
    }

    /**
     * @dev Gets ETH address for a node (convenience function)
     */
    function addr(bytes32 node) external view returns (address payable) {
        return payable(address(bytes20(records[node].addressRecords[60])));
    }

    /**
     * @dev Gets content hash
     */
    function contenthash(bytes32 node) external view returns (bytes memory) {
        return records[node].contenthash;
    }

    /**
     * @dev Gets an ENSIP-24 data record
     */
    function data(bytes32 node, string memory key) external view returns (bytes memory) {
        return records[node].dataRecords[key];
    }

    /**
     * @dev Returns the human-readable label for a node
     * @param node The node to get the label for
     * @return string The human-readable label
     */
    function getLabel(bytes32 node) external view returns (string memory) {
        return records[node].label;
    }

    // Lock Management Functions

    /**
     * @dev Locks a subdomain to "emancipate" it - parent gives up control over the subdomain
     * Only the parent can emancipate their subdomains
     * @param parentNode The parent node (caller must own this or be a registrar)
     * @param labelhash The keccak256 hash of the subdomain label
     * @param lockExpiration The timestamp when the emancipation expires
     */
    function lockSubdomain(bytes32 parentNode, bytes32 labelhash, uint256 lockExpiration) external authorizedOrRegistrar(parentNode) {
        // Calculate the actual subdomain node
        bytes32 subnode = keccak256(abi.encodePacked(parentNode, labelhash));
        
        // Make sure the lock expiration is greater than the current lock expiration. 
        require(
            lockExpiration > lockExpirations[subnode],
            CannotReduceLockTime(lockExpirations[subnode], lockExpiration)
        );
        
        // Always disable/extend parent transfer mode when locking subdomain
        // This ensures every lock action resets the cooldown period
        _extendTransferModeCooldown(parentNode);

        // Set the lock expiration
        lockExpirations[subnode] = lockExpiration;
        
        emit NodeLockSet(subnode, lockExpiration);
    }

    /**
     * @dev Locks a subdomain and adds an initial lock controller in one transaction
     * @param parentNode The parent node (caller must own this or be a registrar)
     * @param labelhash The keccak256 hash of the subdomain label
     * @param lockExpiration The timestamp when the emancipation expires
     * @param controller The address to add as initial lock controller
     */
    function lockSubdomain(bytes32 parentNode, bytes32 labelhash, uint256 lockExpiration, address controller) external authorizedOrRegistrar(parentNode) {
        bytes32 subnode = keccak256(abi.encodePacked(parentNode, labelhash));
        
        // Make sure the lock expiration is greater than the current lock expiration. 
        require(
            lockExpiration > lockExpirations[subnode],
            CannotReduceLockTime(lockExpirations[subnode], lockExpiration)
        );
        
        // Always disable/extend parent transfer mode when locking subdomain
        // This ensures every lock action resets the cooldown period
        _extendTransferModeCooldown(parentNode);
        
        // Set the lock expiration
        lockExpirations[subnode] = lockExpiration;
        
        // Add the specified controller
        lockExpirationControllers[subnode][controller] = true;
        
        emit NodeLockSet(subnode, lockExpiration);
        emit LockControllerAdded(subnode, controller);
    }

    /**
     * @dev Extends the lock expiration time
     * @param node The node to extend lock for
     * @param newExpiration The new expiration timestamp (must be later than current)
     */
    function extendLock(bytes32 node, uint256 newExpiration) external onlyLockController(node) {

        // Make sure the new expiration is greater than the current expiration. 
        require(
            newExpiration > lockExpirations[node],
            CannotReduceLockTime(lockExpirations[node], newExpiration)
        );
        
        lockExpirations[node] = newExpiration;
        emit LockExtended(node, newExpiration);
    }

    /**
     * @dev Allows parent node owner to add lock controllers to a subnode
     * Uses the same pattern as setSubnodeOwner - parent specifies node + labelhash
     * Only the parent can add new lock controllers, subname owners cannot
     * WARNING: This extends the parent's transfer mode cooldown to prevent front-running attacks
     * @param parentNode The parent node (caller must own this)
     * @param labelhash The keccak256 hash of the subdomain label
     * @param controller The address to add as controller
     */
    function addSubnodeLockController(bytes32 parentNode, bytes32 labelhash, address controller) external authorized(parentNode) {
        bytes32 subnode = keccak256(abi.encodePacked(parentNode, labelhash));
        
        // Always extend parent transfer mode cooldown when adding controllers
        // This prevents front-running attacks where sellers add controllers right before sale
        _extendTransferModeCooldown(parentNode);
        
        lockExpirationControllers[subnode][controller] = true;
        emit LockControllerAdded(subnode, controller);
    }

    /**
     * @dev Allows parent node owner to remove lock controllers from a subnode
     * Can only remove controllers when the lock is NOT active (expired)
     * @param parentNode The parent node (caller must own this)
     * @param labelhash The keccak256 hash of the subdomain label
     * @param controller The address to remove as controller
     */
    function removeSubnodeLockController(bytes32 parentNode, bytes32 labelhash, address controller) external authorized(parentNode) {
        bytes32 subnode = keccak256(abi.encodePacked(parentNode, labelhash));
        
        // Can only remove controllers when lock is NOT active (expired)
        require(
            block.timestamp > lockExpirations[subnode],
            NodeLocked(subnode, lockExpirations[subnode])
        );
        
        lockExpirationControllers[subnode][controller] = false;
        emit LockControllerRemoved(subnode, controller);
    }

    // Lock controllers cannot be removed while lock is active to prevent malicious behavior
    // Once added, controllers remain for the duration of the active lock
    // Parent owners can remove controllers only when lock has expired

    /**
     * @dev Checks if a node is currently locked
     * @param node The node to check
     * @return bool True if the node is locked
     */
    function isLocked(bytes32 node) external view returns (bool) {
        return block.timestamp <= lockExpirations[node];
    }

    /**
     * @dev Gets the lock expiration timestamp for a node
     * @param node The node to check
     * @return uint256 The expiration timestamp (0 if not locked)
     */
    function getLockExpiration(bytes32 node) external view returns (uint256) {
        return lockExpirations[node];
    }

    /**
     * @dev Checks if an address is a lock controller for a node
     * @param node The node to check
     * @param controller The address to check
     * @return bool True if the address is a lock controller
     */
    function isLockController(bytes32 node, address controller) external view returns (bool) {
        return lockExpirationControllers[node][controller];
    }

    // Registrar Management Functions

    /**
     * @dev Adds a registrar for a specific node
     * Only the node owner can add registrars
     * @param node The node to add registrar for
     * @param registrar The address to add as registrar
     */
    function addRegistrar(bytes32 node, address registrar) external authorized(node) {
        registrars[node][registrar] = true;
        emit RegistrarAdded(node, registrar);
    }

    /**
     * @dev Removes a registrar for a specific node
     * Only the node owner can remove registrars
     * @param node The node to remove registrar from
     * @param registrar The address to remove as registrar
     */
    function removeRegistrar(bytes32 node, address registrar) external authorized(node) {
        registrars[node][registrar] = false;
        emit RegistrarRemoved(node, registrar);
    }

    /**
     * @dev Checks if an address is a registrar for a node
     * @param node The node to check
     * @param registrar The address to check
     * @return bool True if the address is a registrar
     */
    function isRegistrar(bytes32 node, address registrar) external view returns (bool) {
        return registrars[node][registrar];
    }

    // Transfer Mode Management Functions

    /**
     * @dev Temporarily disables transfer mode to allow subdomain locking
     * WARNING: This creates a mandatory cooldown period during which the domain
     * cannot be transferred. This prevents front-running attacks where
     * sellers lock subdomains right before a sale.
     * Can be called multiple times to extend the cooldown period.
     * @param node The node to disable transfer mode for
     */
    function disableTransferMode(bytes32 node) external authorized(node) {
        _extendTransferModeCooldown(node);
    }

    /**
     * @dev Internal function to extend transfer mode cooldown
     * Used by lockSubdomain and disableTransferMode to reset cooldown
     * @param node The node to extend transfer mode cooldown for
     */
    function _extendTransferModeCooldown(bytes32 node) internal {
        uint256 disabledUntil = block.timestamp + transferModeLockTime;
        transferModeDisabledUntil[node] = disabledUntil;
        
        emit TransferModeDisabled(node, disabledUntil);
    }

    // Manual re-enable removed to prevent front-running attacks
    // Transfer mode automatically re-enables after cooldown period

    /**
     * @dev Updates the transfer mode lock time (admin only)
     * @param newLockTime The new lock time in seconds (max 1 day)
     */
    function setTransferModeLockTime(uint256 newLockTime) external onlyRole(ADMIN_ROLE) {
        require(
            newLockTime <= MAX_TRANSFER_MODE_LOCK_TIME,
            TransferModeLockTimeTooLong(newLockTime, MAX_TRANSFER_MODE_LOCK_TIME)
        );
        
        transferModeLockTime = newLockTime;
        emit TransferModeLockTimeUpdated(newLockTime);
    }

    /**
     * @dev Checks if a node is currently in transfer mode (default state)
     * @param node The node to check
     * @return bool True if the node is in transfer mode (protected)
     */
    function isInTransferMode(bytes32 node) external view returns (bool) {
        // Transfer mode is enabled by default (when transferModeDisabledUntil[node] == 0)
        // Transfer mode is disabled when block.timestamp < transferModeDisabledUntil[node]
        // Transfer mode re-enables when block.timestamp >= transferModeDisabledUntil[node]
        // This matches the >= comparison used in setOwner/transferNode/burnNode
        return block.timestamp >= transferModeDisabledUntil[node];
    }

    /**
     * @dev Gets when transfer mode will be re-enabled for a node
     * @param node The node to check
     * @return uint256 The timestamp when transfer mode re-enables (0 if already enabled)
     */
    function getTransferModeReEnableTime(bytes32 node) external view returns (uint256) {
        return transferModeDisabledUntil[node];
    }

    // ============ UUPS ============

    function _authorizeUpgrade(address newImplementation) internal override onlyRole(DEFAULT_ADMIN_ROLE) {}

    // ============ STORAGE GAP ============
    // Reserve storage slots for future upgrades
    uint256[50] private __gap;

    // ERC165 Support
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, AccessControlUpgradeable) returns (bool) {
        return interfaceId == 0xecbfada3 || // ENSIP-24 data(bytes32,string)
            super.supportsInterface(interfaceId);
    }
} 

src/resolvers/IENS.sol

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

/// @notice Minimal ENS registry interface for ownership checks
interface IENS {
    function owner(bytes32 node) external view returns (address);
}

/// @notice Minimal NameWrapper interface — ownerOf uses namehash as ERC-1155 token ID
interface INameWrapper {
    function ownerOf(uint256 id) external view returns (address);
}

src/utils/HexUtils.sol

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

library HexUtils {
    /// @dev Convert `hexString[pos:end]` to `bytes32`.
    ///      Accepts 0-64 hex-chars.
    ///      Uses right alignment: `1` &rarr; `0000000000000000000000000000000000000000000000000000000000000001`.
    /// @param hexString The string to parse.
    /// @param pos 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 pos,
        uint256 end
    ) internal pure returns (bytes32 word, bool valid) {
        uint256 nibbles = end - pos;
        if (nibbles > 64 || end > hexString.length) {
            return (bytes32(0), false); // too large or out of bounds
        }
        uint256 src;
        assembly {
            src := add(add(hexString, 32), pos)
        }
        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[pos:end]` to `address`.
    ///      Accepts exactly 40 hex-chars.
    /// @param hexString The string to parse.
    /// @param pos 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 pos,
        uint256 end
    ) internal pure returns (address addr, bool valid) {
        if (end - pos != 40) return (address(0), false); // wrong length
        bytes32 word;
        (word, valid) = hexStringToBytes32(hexString, pos, end);
        addr = address(uint160(uint256(word)));
    }

    /// @dev Convert `hexString[pos:end]` to `bytes`.
    ///      Accepts 0+ hex-chars.
    /// @param pos 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 pos,
        uint256 end
    ) internal pure returns (bytes memory v, bool valid) {
        uint256 nibbles = end - pos;
        v = new bytes((1 + nibbles) >> 1); // round up
        uint256 src;
        uint256 dst;
        assembly {
            src := add(add(hexString, 32), pos)
            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
                }
            }
            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)
                    }
                }
            }
        }
    }
}

src/utils/NameCoder.sol

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

import {HexUtils} from "./HexUtils.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).
///
/// To encode a label larger than 255 bytes, use a hashed label.
/// A label of any length can be converted to a hashed label.
///
/// A hashed label is encoded as "[" + toHex(keccak256(label)) + "]".
/// eg. [af2caa1c2ca1d027f1ac823b529d0a67cd144264b2789fa2ea4d63a67c7103cc] = "vitalik".
/// - always 66 bytes.
/// - matches: `/^\[[0-9a-f]{64}\]$/`.
///
/// w/o hashed labels: `dns.length == 2 + ens.length` and the mapping is injective.
///  w/ hashed labels: `dns.length == 2 + ens.split('.').map(x => x.utf8Length).sum(n => n > 255 ? 66 : n)`.
library NameCoder {
    /// @dev The DNS-encoded name is malformed.
    error DNSDecodingFailed(bytes dns);

    /// @dev A label of the ENS name has an invalid size.
    error DNSEncodingFailed(string ens);

    /// @dev Same as `BytesUtils.readLabel()` but supports hashed labels.
    ///      Only the last labelHash is zero.
    ///      Disallows hashed label of zero (eg. `[0..0]`) to prevent confusion with terminator.
    ///      Reverts `DNSDecodingFailed`.
    /// @param name The DNS-encoded name.
    /// @param idx The offset into `name` to start reading.
    /// @return labelHash The resulting labelhash.
    /// @return newIdx The offset into `name` of the next label.
    function readLabel(
        bytes memory name,
        uint256 idx
    ) internal pure returns (bytes32 labelHash, uint256 newIdx) {
        if (idx >= name.length) revert DNSDecodingFailed(name); // "readLabel: expected length"
        uint256 len = uint256(uint8(name[idx++]));
        newIdx = idx + len;
        if (newIdx > name.length) revert DNSDecodingFailed(name); // "readLabel: expected label"
        if (len == 66 && name[idx] == "[" && name[newIdx - 1] == "]") {
            bool valid;
            (labelHash, valid) = HexUtils.hexStringToBytes32(
                name,
                idx + 1,
                newIdx - 1
            ); // will not revert
            if (!valid || labelHash == bytes32(0)) {
                revert DNSDecodingFailed(name); // "readLabel: malformed" or null literal
            }
        } else if (len > 0) {
            assembly {
                labelHash := keccak256(add(add(name, idx), 32), len)
            }
        }
    }

    /// @dev Same as `BytesUtils.namehash()` but supports hashed labels.
    ///      Reverts `DNSDecodingFailed`.
    /// @param name The DNS-encoded name.
    /// @param idx The offset into name start hashing.
    /// @return hash The resulting namehash.
    function namehash(
        bytes memory name,
        uint256 idx
    ) internal pure returns (bytes32 hash) {
        (hash, idx) = readLabel(name, idx);
        if (hash == bytes32(0)) {
            if (idx != name.length) revert DNSDecodingFailed(name); // "namehash: Junk at end of name"
        } else {
            bytes32 parent = namehash(name, idx);
            assembly {
                mstore(0, parent)
                mstore(32, hash)
                hash := keccak256(0, 64)
            }
        }
    }

    /// @dev Convert DNS-encoded name to ENS name.
    ///      Reverts `DNSDecodingFailed`.
    /// @param dns The DNS-encoded name to convert, eg. `\x03aaa\x02bb\x01c\x00`.
    /// @return ens The equivalent ENS name, eg. `aaa.bb.c`.
    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
            uint256 src;
            uint256 dst;
            while (src < n) {
                uint8 len = uint8(dns[src++]);
                if (len == 0) break;
                uint256 end = src + len;
                if (end > dns.length) revert DNSDecodingFailed(dns); // overflow
                if (dst > 0) v[dst++] = "."; // skip first stop
                while (src < end) {
                    bytes1 x = dns[src++]; // read byte
                    if (x == ".") revert DNSDecodingFailed(dns); // malicious label
                    v[dst++] = x; // write byte
                }
            }
            if (src != dns.length) revert DNSDecodingFailed(dns); // junk at end
            return string(v);
        }
    }

    /// @dev Convert ENS name to DNS-encoded name.
    ///      Hashes labels longer than 255 bytes.
    ///      Reverts `DNSEncodingFailed`.
    /// @param ens The ENS name to convert, eg. `aaa.bb.c`.
    /// @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);
            uint256 start;
            assembly {
                start := add(dns, 32) // first byte of output
            }
            uint256 end = start; // remember position to write length
            for (uint256 i; i < n; i++) {
                bytes1 x = bytes(ens)[i]; // read byte
                if (x == ".") {
                    start = _createHashedLabel(start, end);
                    if (start == 0) revert DNSEncodingFailed(ens);
                    end = start; // jump to next position
                } else {
                    assembly {
                        end := add(end, 1) // increase length
                        mstore(end, x) // write byte
                    }
                }
            }
            start = _createHashedLabel(start, end);
            if (start == 0) revert DNSEncodingFailed(ens);
            assembly {
                mstore8(start, 0) // terminal byte
                mstore(dns, sub(start, add(dns, 31))) // truncate length
            }
        }
    }

    /// @dev Write the label length.
    ///      If longer than 255, writes a hashed label instead.
    /// @param start The memory offset of the length-prefixed label.
    /// @param end The memory offset at the end of the label.
    /// @return next The memory offset for the next label.
    ///              Returns 0 if label is empty (handled by caller).
    function _createHashedLabel(
        uint256 start,
        uint256 end
    ) internal pure returns (uint256 next) {
        uint256 size = end - start; // length of label
        if (size > 255) {
            assembly {
                mstore(0, keccak256(add(start, 1), size)) // compute hash of label
            }
            HexUtils.unsafeHex(0, start + 2, 64); // override label with hex(hash)
            assembly {
                mstore8(add(start, 1), 0x5B) // "["
                mstore8(add(start, 66), 0x5D) // "]"
            }
            size = 66;
        }
        if (size > 0) {
            assembly {
                mstore8(start, size) // update length
            }
            next = start + 1 + size; // advance
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "@unruggable/gateways/=lib/unruggable-gateways/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@eth-optimism/=lib/unruggable-gateways/lib/optimism/packages/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "ds-test/=lib/unruggable-gateways/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "optimism/=lib/unruggable-gateways/lib/optimism/packages/contracts-bedrock/src/",
    "unruggable-gateways/=lib/unruggable-gateways/contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.